Vue中.sync 修饰符:进行父子组件间相互传递数据

.sync 修饰符的作用?
允许 prop 进行双向绑定,以 this.$emit(update:PropName,newValue)的模式触发事件。

就是:

1
<text-document v-bind:title.sync="doc.title"></text-document>

相当于:

1
2
3
4
<text-document
v-bind:title="doc.title"
v-on:update:title="doc.title = $event"
></text-document>

以在index.vue下引入childrenOne子组件为例,使用.sync属性,会在mounted生命周期里面 alert 弹出childrenOne,而不是index

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<template>
<div class="vuexWrap common">
<childrenOne :title.sync="doc.title"></childrenOne>
</div>
</template>
<script type="text/javascript">
import childrenOne from '../../components/childrenOne.vue'
export default{
data () {
return {
doc:{
title:'index'
},
}
},
mounted (){
//childrenOne
alert(this.doc.title);
},
components : {
childrenOne
}
}
</script>

childrenOne.vue的生命周期 mounted 里面通过
this.$emit('update:title', this.newTitle);
设置title属值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<template>
<div class="OneWrap common">
{{title}}
</div>
</template>
<script type="text/javascript">
export default{
props:{
title:""
},
data () {
return {
newTitle:"childrenOne"
}
},
mounted (){
this.$emit('update:title', this.newTitle);
},
}
</script>