前端开发那些事儿

Vue 组件的通信方式

2020-11-22  本文已影响0人  弱冠而不立

props,$emit

父组件传递props到子组件(单项数据流)
子组件触发事件,父组件监听子组件事件触发

// 子组件
Vue.component("my-componet",{
        template: `
            <div>
                <li>{{msg}}</li>
                <button @click='emitToApp'>emitToApp</button>
            </div>
            `,
        props: ['msg'],
        methods: {
            emitToApp() {
                this.$emit("emit-to-app", {
                    msg: "goodbye world"
                })
            }
        }
    })
 < --! 父组件 -->
    <div id="app">
        <ul>
            <my-componet @emit-to-app="watchEmit" :msg="msg"></my-componet>
        </ul>
    </div>
<script>
    var app = new Vue({
        el: '#app',
        data: {
            msg: "hello world"
        },
        methods: {
            watchEmit(params) {
                this.msg = params.msg
            }
        }
    })
</script>

ref,$parent和$children

    <div id="app">
        <my-componet ref="childComponet"></my-componet>
    </div>
    <script>
    var app = new Vue({
        el: '#app',
        mounted(){
            console.log(this.$refs.childComponet);
        },
    })
    </script>

EventBus-中央事件总线 ($emit / $on) 适用于 父子、隔代、兄弟组件通信

这种方法通过一个空的 Vue 实例作为中央事件总线(事件中心),用它来触发事件和监听事件,从而实现任何组件间的通信,包括父子、隔代、兄弟组件。

// Bus/index.js
import Vue from 'vue'
export default new Vue;
//brother1
import Bus from './Bus'
updateBro:function(){
   Bus.$emit('updateBro','第'+this.count+++'次修改兄弟数据');
}
// brother2
import Bus from './Bus'
Bus.$on('updateBro',(msg)=>{
    this.msg=msg;
})

$attrs / $listeners 隔代组件通信

<!-- // A组件 -->
<template>
    <div>
        <h3>A组件: {{message}}</h3>
        <B @changeMessage="changeMessage" sendBMsg="sendB" :sendCMsg="message"></B>
    </div>
</template>
<script>
import B from "./B"
export default {
    name: "A",
    data() {
        return {
            message: "send_C_data_message"
        }
    },
    components: {
        B
    },
    methods: {
        changeMessage(message) {
            this.message = message
        }
    }
}
</script>
<!-- // B组件 -->
<template>
    <div>
        <h4>B组件</h4>
        <C v-bind="$attrs" v-on="$listeners"></C>
    </div>
</template>
<script>
import C from "./C"
export default {
    name: "B",
    props: ["sendBMsg"],
    components: {
        C
    }
}
</script>
<template>
    <div>
        <h5>C 组件</h5>
        <input v-model="cMsg" @input="myIpt"/>
    </div>
</template>
<script>
export default {
    name: "C",
    methods: {
        myIpt(e) {
            this.$emit("changeMessage",e.target.value)
        }
    },
    created() {
        this.cMsg = this.$attrs.sendCMsg
        // sendCMsg,   changeMessage
        console.log(this.$attrs, this.$listeners);
    }}
</script>

provide / inject 隔代组件通信

// A组件(祖先组件)
    provide: {
        provideMsg: "provideMsgToC"
    },
// C组件(子孙组件)
inject: ["provideMsg"] //这里接收到的属性,就可以类似props接收到的属性一样使用

VueX 状态管理工具

上一篇 下一篇

猜你喜欢

热点阅读