sync修饰符
那该多好 Lv2

Vue中的.sync修饰符

在Vue中,子父组件组常用的通信方式就是通过 props 进行数据传递,props 值只能在父组件更新并传递给子组件,在子组件内部是不允许改变传递进来的 props 值,这样做是为了保证数据的单向流通。但有时候,需要在子组件内部改变 props 属性值并更新到组件中,这时就需要用到.sync修饰符

sync修饰符做了两件事

  • 声明要传递的数据
  • 声明自定义事件
    :title.sync就是:title="title" @update:title="title=$event"的缩写

父组件:

1
2
3
<child :title.sync="title"></child>
等同于
<child :title="title" @update:title="title = $event"></child>

子组件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<div class="doc">
<h1 class="title">{{ title }}</h1>
<div class="content"></div>
<button @click="changeTitle">修改标题</button>
</div>
/**************************************************/
props: {
title: {
type: String,
},
},
methods: {
changeTitle() {
this.$emit("update:title", "新标题");
},
},

若要传递的值为一个对象下的多个值,可以通过v-bind.sync="doc"将对象中每个值分别传给子组件

父组件:

1
2
3
4
5
6
7
8
9
10
11
12
<child v-bind.sync="doc"></child>
<script>
export default {
data() {
return {
doc: {
title: "初始标题",
content: "初始内容",
},
};
},
</script>

子组件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<div class="doc">
<h1 class="title">{{ title }}</h1>
<div class="content">{{ content }}</div>
<button @click="changeContent">修改标题</button>
</div>
/**************************************************/
props: {
title: {
type: String,
},
content:{
type: String
}
},
methods: {
changeContent() {
this.$emit("update:content", "新内容");
},
},
 评论