vue总结01--组件通信的8种方式

tech2022-12-04  56

组件通信的几种方式

props (父传子) 父组件中: <template> <div> <mchild1 msg="父亲发送的信息"></mchild1> </div> </template> 子组件中: <template> <div>子组件1--接收 {{msg}}</div> </template> <script> export default { name: "Mchild1", props: { msg: { type: String, default: "" } } } </script> 自定义事件 (子传父) 父组件中: <template> <mchild2 @add="sonAdd"></mchild2> </template> <script> import Mchild2 from "../components/Mchild2"; export default { name: "Message", components: { Mchild2 }, methods: { sonAdd(val) { console.log(val) // 传递过来的值 } } } </script> 子组件中: <template> <div @click="send">子组件2</div> </template> <script> export default { name: "Mchild2", methods: { send() { this.$emit('add', "我是子组件发送给父组件的值"); } } } </script> 事件总线 (子组件1给子组件2发送) 子组件1: <button @click="sendMsgToChild1">给子组件1发送消息</button> sendToChild1() { // 利用事件总线发送事件 this.$bus.$emit('msg-from-1', 'send msg to child2') } 子组件2: this.$bus.$on('msg-from-1', msg => { console.log('fromChild1:', msg); }); main.js里面定义总线: Vue.prototype.$bus = new Vue() vuex(共享状态) store下index.js import Vue from "vue"; import Vuex from "vuex"; Vue.use(Vuex); export default new Vuex.Store({ state: { num: 0 }, mutations: { SET_NUM: (state, num) => { state.num = num; } }, actions: { setNum: ({ commit }, num) => { return commit("SET_NUM", num); } }, modules: {} }); 然后就可以在组件中共享状态了 通过dispatch调用action即可 this.$store.dispatch('setNum',this.num); vuex主要成员 state 存放状态,也就是共享值 mutations state成员操作 getters 包装state成员给外界 actions 异步操作 modules 模块化状态管理 $parant/$root(子组件和子组件) 兄弟组件之间通信可通过共同祖辈搭桥通信,$parent或$root 同样适用子组件1来给子组件2发送信息 子组件1: this.$parent.$emit('pSendMsgToChild2', "我是通过parent来发送的"); 子组件2: this.$parent.$on('pSendMsgToChild2', msg => { alert(msg) }) $root和$parant用法一样 $children/$refs ⽗组件可以通过$children访问⼦组件实现⽗⼦通信。 $children获取子组件数组,因为不包括普通元素,所以不保证模板中顺序 在父组件中: this.$children[0].xx = 'xxx'即可 使用$refs,在父组件中 <Mchild1 ref="xnn"/> mounted() { this.$refs.xnn.xx = 'xxx' } $attrs/$listeners 包含了⽗作⽤域中不作为 prop 被识别 (且获取) 的特性绑定 (class 和 style 除外)。也就是说,假如我父组件中传值了,但是子组件中并没有用props声明,那么子组件中都可以使用$attrs来获取。 父组件中: <mchild2 ms="ms"></mchild2> 子组件: {{$attrs.ms}} // 打印ms 在父组件中给子组件绑定的方法,都可以用$listeners调用 父组件中: <mchild2 @kk="kk"></mchild2> kk() { console.log('kk') } 子组件中: this.$listeners.kk(); // 打印出kk provide/inject 能够实现祖先和后代之间传值 父组件: provide() { return { message: '要传递的值' } } 子组件中: inject: ['message'] 然后就可以打印出这个玩意看看!!! console.log(this.message) // 打印出 "要传递的值" 当然孙子组件也是可以获取到的!!
最新回复(0)