vue跨页面调用函数

一.父子组件

parent.vue

<div class="parent">
      <child
        ref="child"
        @saveData="save"
      />
</div>
<el-button  @click="callChild" >下一步</el-button>


methods: {
	callChild() {
      this.$refs.child.submitData();//父组件调用子组件
    },
    save(params) {
    	console.log('getChild',params)
    }
}

child.vue

<div class="child">
     
<el-button  @click="callParent" >下一步</el-button>


methods: {
	callParent() {
      this.$emit("saveData", data);//子组件调用父组件
    },
    submitData(){
    	console.log('getParent')
    }
}

二.非父子组件

1.依赖mitt库

1.安装mitt库

npm install mitt 

2.引入库并创建事件总线对象
MyBus.js

import mitt from "mitt";
const bus = {};
const emitter = mitt();
bus.$on = emitter.on;
bus.$off = emitter.off;
bus.$emit = emitter.emit;
export default bus

3.引入
main.js

import { createApp } from 'vue'
import App from './App.vue'
import Bus from './utils/MyBus'

const app = createApp(App)
app.config.globalProperties.$EventBus = Bus

4.调用

this.$EventBus.$emit("setData", data);//在发送方组件中触发事件

this.$EventBus.$on("setData", (data) => {//在接收方组件中监听事件
    console.log(data)
});

2.创建中间件

1.创建中间件middl.js

// 中间件 实现跨页面调用方法
import Vue from 'vue'
export default new Vue

2.调用

import Middle from "@/utils/middle.js";
Middle.$emit("setData", data);//在发送方组件中触发事件

Middle.$on("setData", (data) => {//在接收方组件中监听事件
    console.log(data)
});

3.vuex

通过在Vuex中定义全局方法,在组件中通过$store.dispatch调用全局的Vuex方法

1.定义store
store/index.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    msg:'hello',
  },
  mutations: {
    changeMsg(state){
      state.msg='hello world';
    }
  },
  actions:{
    changeMsg({commit}){
      commit('changeMsg');
    }
  }
})

export default store;

2.调用

this.$store.dispatch('changeMsg');

你可能感兴趣的:(vue,vue.js,javascript,前端)