组件自定义事件之 .sync 修饰符

组件自定义事件之 .sync 修饰符

  • 在没有 .sync 修饰符之前我们要对一个 prop 进行双向绑定。

可直接复制以下代码查看

<!--父组件模板-->
<div id="app">
    {{father}}
    <button @click="btnClick">父组件按钮</button>
    <son :son.sync="father"></son>
</div>
<!--子组件模板-->
<template id="son">
	  <div>
          {{son}}
	    <button @click="btnClick">子组件按钮</button>
	  </div>
	</template>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<script>
    // 1.子组件
    const son = {
        template: '#son',
        props: {
            son: String
        },
        methods: {
            btnClick(item) {
                // 发射事件: 自定义事件
                this.$emit('update:son', 'hello World')
            }
        }
    }
    // 2.父组件
    const app = new Vue({
        el: '#app',
        data: {
            father: 'lazy'
        },
        // 注册组件
        components: {
            son
        },
        methods: {
            btnClick() {
                this.father = '老司机';
            }
        }
    })
</script>
  • 这里我们将父组件的 father 变量和 prop 的 son 进行绑定
  • 然后在子组件放射自定义事件来改变父组件 father 的值
  • 为了方便起见,我们可以将子组件进行一个缩写
  • 注意事件名要以 update: 加上需要绑定的 prop字段名 的字符串
<son :son.sync="father"></son>
  • son 代表 prop 绑定的变量及发射自定义事件 update: 后跟的字符串

  • father 代表 父组件绑定给子组件的变量

  • 这样我们无论在父组件还是子组件都可以改变这一对“双向绑定”的变量

一个对象同时设置多个 prop

<!--父组件模板-->
<div id="app">
    {{father.son}}
    <button @click="btnClick">父组件按钮</button>
    <son v-bind.sync="father"></son>
</div>
<!--子组件模板-->
<template id="son">
	  <div>
          {{son}}
          {{son2}}
	    <button @click="btnClick">子组件按钮</button>
	  </div>
	</template>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<script>
    // 1.子组件
    const son = {
        template: '#son',
        props: {
            son: String,
            son2: String
        },
        methods: {
            btnClick(item) {
                // 发射事件: 自定义事件
                this.$emit('update:son', 'hello World')
                this.$emit('update:son2', 'hello World2')
            }
        }
    }
    // 2.父组件
    const app = new Vue({
        el: '#app',
        data: {
            father: {
                son: 'son1',
                son2: 'son2'
            }
        },
        // 注册组件
        components: {
            son
        },
        methods: {
            btnClick() {
                this.father.son = '老司机';
                this.father.son2 = '老司机2';
            }
        }
    })
</script>
  • 这样会把 father 对象中的每一个 property (如 son) 都作为一个独立的 prop 传进去,然后各自添加用于更新的 v-on 监听器。

注意 v-bind 不能用语法tangibl糖 : 代替,会语法报错

将 v-bind.sync 用在一个字面量的对象上,例如 v-bind.sync=”{ title: doc.title }”,是无法正常工作的,因为在解析一个像这样的复杂表达式的时候,有很多边缘情况需要考虑。

posted @ 2021-01-18 20:43  懒惰ing  阅读(257)  评论(0)    收藏  举报