Vue的数据双向绑定例子
可以参考该网址https://www.cnblogs.com/xxcanghai/p/6124699.html
我写的这个是使用vue-cli编写的一个例子。
以下是父组件源码,绑定了一个对象然后使用props在子组件获取(此为单项绑定)。
<template>
<div>
<table id="person-message">
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>操作</th>
</tr>
<tr v-for="(person,index) in persons"
:key="person.id"
is="sideler"
:person="{
name:person.name,
age:person.age,
sex:person.sex,
isEdit:person.show,
}"
@edit="contentEdit"
@remove="persons.splice(index,1)"
@update="updateData"
>
</tr>
</table>
</div>
</template>
<script>
import Sideler from "./Sideler"
export default {
name: 'bulbmain',
components:{
Sideler
},
methods:{
contentEdit(event){
if(event.target.textContent == '编辑')
{
event.target.textContent = '保存'
}
else if(event.target.textContent == '保存')
{
event.target.textContent = '编辑'
}
},
updateData(val){
this.persons = val //外层调用组件方注册变更方法,将组件内的数据变更,同步到组件外的数据状态中
}
},
data(){
return {
persons:[
{
name: 'Nick',
age: 26,
sex: '男',
show: true
},
{
name: 'Nick',
age: 26,
sex: '男',
show: true
},
{
name: 'Nick',
age: 26,
sex: '男',
show: true
},
{
name: 'Nick',
age: 26,
sex: '男',
show: true
},
{
name: 'Nick',
age: 26,
sex: '男',
show: true
},
{
name: 'Nick',
age: 26,
sex: '男',
show: true
},
{
name: 'Nick',
age: 26,
sex: '男',
show: true
},
]
}
}
}
</script>
<style >
#person-message{
text-align: center;
}
#person-message th{
width: 100px;
}
#person-message tr input{
text-align: center;
width: 50px;
}
</style>
以下是子组件源码:
通过props接收父组件传递过来的data,并建立一个data副本,v-model绑定了data副本,修改其中的数据并不会影响到props中传递过来的数据,所以创建一个watch对象监听子组件中data的修改并将变更向其父组件通知。由父组件修改data
<template>
<tr>
<td>
<span v-if="childData.isEdit">{{ childData.name }}</span>
<input v-else type="text" v-model="childData.name">
</td>
<td>
<span v-if="childData.isEdit">{{ childData.age }}</span>
<input v-else type="number" v-model="childData.age">
</td>
<td>
<span v-if="childData.isEdit">{{ childData.sex }}</span>
<input v-else type="text" v-model="childData.sex">
</td>
<td>
<button @click="$emit('edit',$event,childData.isEdit = !childData.isEdit)">编辑</button>
<button @click="$emit('remove')">删除</button>
</td>
</tr>
</template>
<script>
export default {
name: 'sideler',
props:{
person:{
type: Object,
required: true
}
},
data(){
return {
childData: this.person //创建props属性person的副本
}
},
watch:{
'person'(val){
this.childData = val //监听外部对props属性person的变更,并同步到组件内的data属性childData中
},
'childData'(val){
this.$emit('update',val) //组件内对childData变更后向外部发送事件通知
}
}
}
</script>
以上为个人的理解,如果有不足之处或者不解之处欢迎探讨。