vue.js中$emit的理解


官網介紹比較簡單

例子:$emit('increment1',[12,'kkk']),直接看是懵逼的有沒有,可以先告訴你,就是觸發自定義事件increment1(或者函數名吧),[]為參數

上案例

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="counter-event-example">
            <p>{{ total }}</p>
            <button-counter v-on:increment1="incrementTotal"></button-counter>
            <button-counter v-on:increment2="incrementTotal"></button-counter>
        </div>
    </body>
    <script src="vue/vue.min.js"></script>
    <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('increment1',[12,'kkk']);//$emit
                }
            }
        });
        new Vue({
            el:'#counter-event-example',
            data:{
                total:0
            },
            methods:{
                incrementTotal:function(e){
                    this.total += 1;
                    console.log(e);
                }
            }
        });
    </script>
</html>

先看組件 button-counter

綁定了事件click————>increment

然后 this.counter += 1; this.$emit('increment1',[12,'kkk']);

這邊就是觸發事件 increment1,參考文獻里面有點亂,這邊是不是清晰多了

然后 <button-counter v-on:increment1="incrementTotal"></button-counter> 

v-on相當於監聽吧,就觸發 incrementTotal

輸出// [12, "kkk"]

有沒有很清晰,若有理解不對的地方,請指正

 
        

 

 

 

 

參考:http://arinu.me/?p=50


免責聲明!

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



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