1. 程式人生 > >Vue 組件通信(組件間通信)

Vue 組件通信(組件間通信)

app () meta log mes msg mit class 應急

1、中央事件總線bus

<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <title>Vue</title>
    </head>

    <body>
        <div id="app">
            <p>{{message}}</p>
            <my-component></
my-component> </div> <script src="https://cdn.bootcss.com/vue/2.5.9/vue.min.js"></script> <script type="text/javascript"> var bus = new Vue(); Vue.component(my-component, { template: `<button @click="handleEvent
">傳遞事件</button>`, methods: { handleEvent: function() { bus.$emit(on-message, 來自組件my-component的內容) } } }) new Vue({ el: "#app", data: { message:
‘‘ }, mounted: function() { var _this = this; //監聽來自bus實例的事件 bus.$on(on-message, function(msg) { _this.message = msg; }) } }) </script> </body> </html>

2、父鏈

<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <title>Vue</title>
    </head>

    <body>
        <div id="app">
            <p>{{message}}</p>
            <my-component></my-component>
        </div>
        <script src="https://cdn.bootcss.com/vue/2.5.9/vue.min.js"></script>
        <script type="text/javascript">
            Vue.component(my-component, {
                template: `<button @click="handleEvent">通過父鏈修改數據</button>`,
                methods: {
                    handleEvent: function() {
                        this.$parent.message = 來自組件my-component的內容
                    }
                }
            })
            new Vue({
                el: "#app",
                data: {
                    message: ‘‘
                }
            })
        </script>
    </body>

</html>

註:盡量少用,父子組件最好通過props和$emit來通信

3、子組件索引

<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <title>Vue</title>
    </head>

    <body>
        <div id="app">
            <button @click="handleRef">獲取子組件內容</button>     
            <p>父組件:{{message}}</p>
            <my-component ref=‘comA‘></my-component>
        </div>
        <script src="https://cdn.bootcss.com/vue/2.5.9/vue.min.js"></script>
        <script type="text/javascript">
            Vue.component(my-component, {
                template: <div>子組件</div>,
                   data:function(){
                       return {
                           message:子組件內容
                       }
                   }
            });
            new Vue({
                el: "#app",
                data:{
                    message:‘‘
                },
                   methods:{
                       handleRef:function(){
                           var msg = this.$refs.comA.message;     
                           this.message = msg;
                       }
                   }
            })
        </script>
    </body>

</html>

註:僅僅作為直接訪問子組件的應急方案,避免在模板或者計算屬性中使用$refs.

Vue 組件通信(組件間通信)