一、表单输入绑定
- 使用v-model(双向数据绑定)自动收集数据
text/textarea
checkbox
radio
select
<div id="demo">
<!-- 点击按钮 @submit提交
点击按钮 @submit.prevent 不提交-->
<form action="/xxx" @submit.prevent="handleSubmit">
<span>用户名: </span>
<input type="text" v-model="username"><br>
<span>密码: </span>
<input type="password" v-model="pwd"><br>
<span>性别radio: </span>
<input type="radio" id="female" value="女" v-model="sex">
<label for="female">女</label>
<input type="radio" id="male" value="男" v-model="sex">
<label for="male">男</label><br>
<span>爱好checkbox: </span>
<input type="checkbox" id="basket" value="basket" v-model="likes">
<label for="basket">篮球</label>
<input type="checkbox" id="foot" value="foot" v-model="likes">
<label for="foot">足球</label>
<input type="checkbox" id="pingpang" value="pingpang" v-model="likes">
<label for="pingpang">乒乓</label><br>
<span>城市select: </span>
<select v-model="cityId">
<option value="">未选择</option>
<!--:value="city.id" 表达式;value="city.id"文本 -->
<option :value="city.id" v-for="(city, index) in allCitys" :key="city.id">{{city.name}}</option>
</select><br>
<span>介绍textarea: </span>
<textarea rows="10" v-model="info"></textarea><br><br>
<input type="submit" value="注册">
</form>
</div>
<script type="text/javascript">
new Vue({
el: '#demo',
data: {
username: '',
pwd: '',
sex: '男', // 默认显示 男
likes: ['foot'], // 默认显示 足球
allCitys: [{id: 1, name: 'BJ'}, {id: 2, name: 'SS'}, {id: 3, name: 'SZ'}],
cityId: '2', // 默认展示第2个城市
info: ''
},
methods: {
handleSubmit () {
console.log(this.username, this.pwd, this.sex, this.likes, this.cityId, this.info)
alert('提交注册的ajax请求')
}
}
})
</script>
二、Vue实例生命周期:
- vue对象的生命周期
1). new vue()初始化显示
* beforeCreate()
* created()
* beforeMount()
* mounted()
2). 更新状态
this.xxx = value
* beforeUpdate()
* updated()
3). 销毁vue实例: vm.$destory()
* beforeDestory()
* destoryed()
- 常用的生命周期方法
created()/mounted(): 发送ajax请求, 启动定时器等异步任务
beforeDestory(): 做收尾工作, 如: 清除定时器
完整生命周期图
<div id="test">
<button @click="destroyVue">销毁vue</button>
<p v-if="isShow">vue</p>
</div>
<script type="text/javascript">
new Vue({
el: '#test',
data: {
isShow: true
},
// 初始化:执行一次
beforeCreate() {
console.log('beforeCreate()')
},
created() {
console.log('created()')
},
berforeMount() {
console.log('berforeMount()')
},
mounted () {
// 执行异步任务
// this.intervalld 全局的定时器
this.intervalId = setInterval(() => {
this.isShow = !this.isShow
}, 1000)
},
// 更新
beforeUpdate() {
console.log('beforeUpdate()')
},
updated() {
console.log('updated()')
},
// 销毁
beforeDestroy() {
console.log('beforeDestroy()');
// 执行收尾的工作,清除定时器,否则内存溢出
clearInterval(this.intervalId);
},
destoryed() {
console.log('destoryed()');
}
methods: {
destroyVue () {
// 销毁vm
this.$destroy()
}
}
})