Vue父组件刷新方法详解·prototype·在子组件中使用$emit触发一个事件

Vue父组件刷新方法详解

一、事件总线(Event Bus)

事件总线就像一个交通警察,负责让不同组件之间传递信息。

创建事件总线:在main.js中初始化一个Event Bus实例。


// main.js

import Vue from 'vue';

Vue.prototype.$bus = new Vue();

在子组件中发送消息:使用$bus.$emit发送事件。


// 子组件中

this.$bus.$emit('refreshEvent');

在父组件中监听事件:使用$bus.$on监听事件。


// 父组件中

this.$bus.$on('refreshEvent', this.refreshMethod);

二、Vuex状态管理

Vuex就像是项目的大脑,管理着所有组件间的状态。

安装Vuex:在项目中安装Vuex。

创建store:定义一个刷新状态。


// store.js

const store = new Vuex.Store({

  state: {

    refreshing: false

  },

  mutations: {

    setRefreshing(state, status) {

      state.refreshing = status;

    }

  }

});

在子组件中触发状态改变:通过store.commit改变状态。


// 子组件中

this.$store.commit('setRefreshing', true);

在父组件中监听状态变化:使用watch监听状态变化。


// 父组件中

this.$watch('refreshing', this.refreshMethod);

三、使用$emit方法

使用$emit就像是在组件间搭了一座桥梁。

在子组件中使用$emit:触发一个事件。


// 子组件中

this.$emit('refresh');

在父组件中监听事件:监听子组件触发的事件。


// 父组件中

this.$on('refresh', this.refreshMethod);

四、使用refs属性

refs就像是一个指针,直接指向子组件。

在子组件中定义方法:定义一个方法触发父组件的刷新。


// 子组件中

methods: {

  refreshParent() {

    this.$parent.refreshMethod();

  }

}

在父组件中使用refs:通过refs访问子组件实例并调用方法。


// 父组件中