使用
- 在html文件中通过以下方式引入Vue:
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
- 开始使用
案例
实现效果
向firstName和lastName中输入内容,会同时显示到fullName,fullName2,fullName3中,其中改变fullName3的值,firstName和lastName的值也会改变
<div id="app">
firstName:<input type="text" v-model="firstName"><br/>
lastName:<input type="text" v-model="lastName"><br/>
fullName(单向):<input type="text" v-model="fullName1"><br/>
fullName2(单向):<input type="text" v-model="fullName2"><br/>
firstName3(双向):<input type="text" v-model="fullName3"><br/>
</div>
代码
- 起到一个数据双向绑定的作用
v-model
<script>
new Vue({
el: '#app',
data(){
return {
firstName: '',
lastName: '',
fullName2: '',
}
},
//使用计算属性
computed: {
fullName1: function(){
/*let firstName = this.firstName
let lastName = this.lastName*/
return this.firstName+' '+this.lastName
},
fullName3: {
get() {
return this.firstName+' '+this.lastName
},
set(value) {
let names = value.split(/\s+/)
this.firstName=names[0]
this.lastName=names[1]
}
}
},
//使用监听器
watch: {
firstName: function(newVal,oldVal){
this.fullName2 = newVal+' '+this.lastName
},
lastName: function(newVal,oldVal){
this.fullName2=this.firstName+' '+newVal
}
}
})
</script>
new Vue({ })//第一步
- 起类似选择器作用
el: ‘#app’
- 注意Vue中的数据尽量使用以下格式
data(){
return{
}
}
- 计算属性 ,其中的值可以不在data中定义
computed: { }
- 回调函数fullName1,当函数中的firstName和lastName发生改变时,触发函数
fullName1: function(){
let firstName = this.firstName
let lastName = this.lastName
return firstName+' '+lastName
}
相当于
fullName1:{
get(){
}
}
- 当value值改变时触发函数set(value){}
fullName3: {
set(value) {
}
}
- 监听器,对v-model=‘firstName’进行监听,newVal表示改变后的值,oldVal表示原来的值
watch: {
firstName: function(newVal,oldVal){
this.fullName2 = newVal+' '+this.lastName
}
}