vue .sync修饰符的使用详解修饰符的使用详解
vue的官网介绍非常不错,先通读一遍。
2.3.0+ 新增
在有些情况下,我们可能需要对一个 prop 进行“双向绑定”。不幸的是,真正的双向绑定会带来维护上的问题,因为子组件可
以修改父组件,且在父组件和子组件都没有明显的改动来源。
这也是为什么我们推荐以 update:my-prop-name 的模式触发事件取而代之。举个例子,在一个包含 title prop 的假设的组件中,我
们可以用以下方法表达对其赋新值的意图:
this.$emit('update:title', newTitle)
然后父组件可以监听那个事件并根据需要更新一个本地的数据属性。例如:
<text-document
v-bind:title="doc.title"
v-on:update:title="doc.title = $event"
></text-document>
为了方便起见,我们为这种模式提供一个缩写,即 .sync 修饰符:
<text-document v-bind:title.sync="doc.title"></text-document>
当我们用一个对象同时设置多个 prop 的时候,也可以将这个 .sync 修饰符和 v-bind 配合使用:
<text-document v-bind.sync="doc"></text-document>
这样会把 doc 对象中的每一个属性 (如 title ) 都作为一个独立的 prop 传进去,然后各自添加用于更新的 v-on 监听器。
以下为代码实例
father.vue
<template>
<div class="hello">
//input实时改变wrd的值, 并且会实时改变box里的内容
<input type="text" v-model="wrd">
<box :word.sync="wrd" ></box>
</div>
</template>
<script>
import box from './box' //引入box子组件
export default {
name: 'HelloWorld',
data() {
return {
wrd: ''
}
},
components: {
box
}
}
</script>
child.vue
<template>
<div class="hello">
<div class="ipt">
<input type="text" v-model="str">
</div>
//word是父元素传过来的
<h2>{{ word }}</h2>
</div>
</template>
<script>
export default {
name: 'box',
data() {
return {
str: '',
}