组件自定义事件(.sync)实例

     
        <div id="root">
          <parent></parent>
       </div>
     var childNode = {
            template:'\
                <div class="child">\
                    <div>子组件数据 {{ childMsg }} </div>\
                    <input v-model="childMsg">\
                    <button v-on:click="add">+1</button>\ //第一步:点击按钮
                </div>\
            ',
            data:function(){
                return {
                    childMsg:0
                }
            },
            methods:{
                add:function(){ //第二步:触发add方法,再触发update:foo,用childMsg更新foo,由于.sync的缘由,数据变成了双向绑定 更改foo一样也更改了父组件的msg属性
                    this.childMsg++
                    this.$emit('update:foo',this.childMsg)
                }
            }
        }
        var parentNode = {
            template:'\
                <div class="parent">\
                    <p>父组件数据 {{ msg }} </p>\
                    <child :foo.sync="msg"></child>\ //(v-bind:foo 给子组件绑定一个foo属性,把父组件的属性msg赋值子组件的foo)
                </div>\
            ',
            components:{
                'child':childNode
            },
            data:function(){
                return {
                    msg:0
                }
            }
        }
        new Vue({
            el:'#root',
            components:{
                'parent':parentNode
            }
        })
DOM渲染的结果为:
相关文章
相关标签/搜索