Vue-父传子、子传父、任意组件之间的通信方法

父组件向子组件传值:

props

父组件:

<template>
    <div>
        <child :age="age" ></child>
    </div>
</template>
<script>
    import Child from './' 
    export default{
        data(){
            return {age:'XX'}
        },
        components:{
            Child
        }
    }
</scritp>

子组件:

<template>
    <div>{
   
   {age}}</div>
</template>
<script>
export default{
    name: "Child",
    props:['age'],//or props:{name:String}}
}
</script>

子组件向父组件传值:

$emit

子组件:

<template>
    <div @click="changeAge('YY')">{
   
   {age}}</div>
</template>
<script>
export default{
    props:['age'],//or props:{age:String}
    methods:{
        changeAge(newAge){
            this.$emit('changeAge',newAge)
        }
    }
}
</script>

父组件:

<template>
    <div>
        <child @changeAge="changeAge"></child>
    </div>
</template>
<script>
    import Child from './'
    export default{
        data(){
            return {age:'XX'}
        },
        components:{
            Child
        },
        methods:{
            changeAge(newAge){
                this.age = newAge;
            }
        }
    }
</scritp>

ref

        在父组件内通过ref获取子组件实例,然后调用子组件方法,并传递相关数据作为参数。

标识:ref="xxx"

获取:this.$refs.xxx

子组件:

<template>
    <div>{
   
   {parentMsg}}</div>
</template>
<script>
export default{
    data(){
        return {
            parentMsg:''
        }
    },
    methods:{
        getMsg(msg){
            this.parentMsg = msg;
        }
    }
}
</script>

父组件:

<template>
    <div>
        <child ref="child"></child>
        <button @click="sendMsg">SEND MESSAGE</button>
    </div>
</template>
<script>
    import Childfrom './'
    export default{
        components:{
            Child
        },
        methods:{
            sendMsg(){
                this.$refs.child.getMsg('Parent Message');
            }
        }
    }
</scritp>

 兄弟组件传值:

事件总线

import Vue from 'vue';
const eventBus= new Vue()  //创建事件总线
export default eventBus;

传递值:使用$emit发布事件 

import eventBus from '@u/eventBus'

eventBus.$emit('send',‘hello')

 接收值:使用$on订阅事件 

import eventBus from '@u/eventBus'

eventBus.$on('send', msg )=> {
    console.log(msg)  //控制台输出 hello
}

        注意:$on先进行监听,一旦$emit发布事件后所有组件都可以$on监听到事件。所以传递参数的时候一定已经先进行了监听才能得到参数。比如在父组件中$emit事件放在mounted钩子函数中,等待子组件创建并$on开始监听事件后再去触发$emit发布事件。

$off()移除事件监听

import eventBus from '@u/eventBus'

eventBus.$off('send')  

消息订阅与发布

事件订阅功能$on是$eventBus对象完成的,与组件无关,如果用v-if销毁子组件的时候,会形成闭包,造成内存泄露,所有要在销毁组件的时候进行取消监听事件

1、一种组件间通信的方式,适用于任意组件间通信。

2、使用步骤:

(1)安装pubsub:npm i pubsub-js

(2)引入:import pubsub from 'pubsub-js'

3、接收数据:A组件想接收数据,则在A组件中订阅消息,订阅的回调留在A组件自身。

methods(){
  demo(data){......}
}
......
mounted(){
  this.pid = pubsub.subscribe('xxx',this.demo)//订阅消息
}

4、提供数据:pubsub.publish('xxx',数据)

5、最好在beforeDestroy钩子中,用PubSub.unsubscribe(pid)去取消订阅。

nextTick
1、语法:this.$nextTick(回调函数)

2、作用:在下一次DOM更新结束后执行其指定的回调

3、什么时候用:当改变数据后,要基于更新后的新DOM进行某些操作时,要在nextTick所指定的回调函数中执行。

vuex

1、概念:专门在Vue中实现集中式状态(数据)管理的一个Vue插件,对vue应用中多个组件的共享状态进行集中式的管理(读/写),也是一种组件间通信的方式,且适用于任意组件间通信。

2、Github地址: https://github.com/vuejs/vuex

什么时候使用vuex
1、多个组件依赖于同一状态

2、来自不同组件的行为需要变更同一状态

Vuex 工作原理图


搭建vuex环境
1、创建文件: src/store/index.js

//该文件用于创建vuex中最为核心的store

//引入Vue核心库
import Vue from "vue"
//引入Vuex
import Vuex from "vuex"
//应用Vuex插件
Vue.use(vuex)

//准备actions——用于响应组件中的对象
const actions ={}
//准备mutations——用于操作数据(state)
const mutations = {}
//准备state——用于存储数据
const state = {}


//创建并暴露store
export default new Vuex.Store({
    actions:actions,
    mutations,
    state,
})
2、在main.js中创建vm时传入store配置项

//引入store
import store from "./store"
......

//创建vm
new Vue({
    el:"app",
    render:h=>h(App),
    store,
})

基本使用
1、初始化数据、配置actions、配置mutations,操作文件store.js

//引入Vue核心库
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//引入Vuex
Vue.use(Vuex)

const actions = {
  //响应组件中加的动作
  jia(context,value){
    context.conmmit('JIA',value)
  },
}

const mutations = {
  //执行加
  JIA(state,value){
    state.sum += value
  }
}

//初始化数据
const state = {
  sum:0
}

//创建并暴露store
export dafault new Vuex.store({
  actions,
  mutations,
  state,
})

2、组件中读取vuex中的数据:$store.state.sum

3、组件中修改vuex中的数据:$store.dispatch('action中的方法名',数据)或$store.commit(mutations中的方法名',数据)

备注:若没有网络请求或其他业务逻辑,组件中也可以越过actions,即不写dispatch,直接编写commit

getters的使用
1、概念:当state中的数据需要经过加工后再使用时,可以使用getters加工

2、再store.js中追加getters配置

......
const getters = {
  bigSum(state){
    return state.sum = 10
  }
}

//创建并暴露store
export dafault new Vuex.Store({
  ......
  getters
})

3、组件中读取数据:$store.getters.bigSum
 

猜你喜欢

转载自blog.csdn.net/m0_53206841/article/details/125406571