美文网首页
深入理解vue .sync修饰符

深入理解vue .sync修饰符

作者: zhao_ran | 来源:发表于2020-05-22 22:53 被阅读0次

    .sync是vue中用于实现简单的“双向绑定”的语法糖,在平时的开发中是非常使用的。

    vue的prop是单向下行绑定:父级的prop的更新会向下流动到子组件中,但是反过来不行。可是有些情况,我们需要对prop进行“双向绑定”。这个时候,就可以用.sync来解决

    .sync用法
    <text-document :title.sync="doc.title"></text-document>
    
    当子组件需要更新 title 的值时,它需要显式地触发一个更新事件:
    this.$emit('update:title', newValue)
    
    这样title的属性在子组件内部更新,父组件也能感知的到,实现了“双向绑定”
    .sync应运简单实例
    <template>
        <div class="details">
            <myComponent :show.sync='valueChild' style="padding: 30px 20px 30px 5px;border:1px solid #ddd;margin-bottom: 10px;"></myComponent>
            <button @click="changeValue">toggle</button>
        </div>
    </template>
    <script>
    import Vue from 'vue'
    Vue.component('myComponent', {
          template: `<div v-if="show">
                        <p>默认初始值是{{show}},所以是显示的</p>
                        <button @click.stop="closeDiv">关闭</button>
                     </div>`,
          props:['show'],
          methods: {
            closeDiv() {
              this.$emit('update:show', false); //触发 input 事件,并传入新值
            }
          }
    })
    export default{
        data(){
            return{
                valueChild:true,
            }
        },
        methods:{
            changeValue(){
                this.valueChild = !this.valueChild
            }
        }
    }
    </script>
    
    总结

    如果未触发事件 this.$emit('update:show', false); 则外部感知不到子组件内部对show的改变,依然认为此事的值是true,导致弹框点击打开一次之后,后面再不会打开。

    相关文章

      网友评论

          本文标题:深入理解vue .sync修饰符

          本文链接:https://www.haomeiwen.com/subject/vfrhahtx.html