組件自定義事件(.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渲染的結果爲:
相關文章
相關標籤/搜索