Vue 子組件向父組件傳參


直接上代碼

  

<body>
    <div id="counter-event-example">
      <p>{{ total }}</p>
      <button-counter v-on:ee="incrementTotal"></button-counter>
      <button-counter v-on:ee="incrementTotal"></button-counter>
    </div>

    <script>
        Vue.component('button-counter', {
          template: '<button v-on:click="increment">{{ counter }}</button>',
          data: function () {
            return {
              counter: 0
            }
          },
          methods: {
            increment: function () {
              this.counter += 1
              this.$emit('ee', 'cc' )
            }
          },
        })
        new Vue({
          el: '#counter-event-example',
          data: {
            total: 'arg'
          },
          methods: {
            incrementTotal: function (b) {
              this.total  = b + '1';
            }
          }
        })
    </script>
</body>

  子組件通過$emit觸發父組件的事件,$emit后面的參數是向父組件傳參,注意,父組件的事件處理函數直接寫函數名即可,不要加(),參數直接傳遞到了父組件的methods的事件處理函數了。

  結果

 點擊幾次后變成 

 

 

  另外,寫一個小拾遺。vue子組件用了定義模板組件功能,然后在父組件里定義一個HTML元素綁定這個子組件后才能在父組件通過這個HTML元素使用。

 

  再說一個非常方便的v-ref

<body>
    <div id="parent">
        <user-profile v-ref:profile></user-profile>
    </div>

    <script>
        Vue.component('user-profile', {
            template: '<span>{{ msg }}</span>',
            data: function () {
                return {msg: 123};
            },
            methods: {
                greet: function () {
                    console.log('hhhhh');
                }
            }

        })
        var parent = new Vue({el: '#parent'});
        var child = parent.$refs.profile;
        child.greet();
    </script>
</body>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM