1、bus總線
//定義bus插件
//在util文件夾下定義bus.js
import Vue from 'vue'; let install = (vue) => { vue.prototype.bus = new Vue(); } export default install;
1.1、用到bus總線的地方,兄弟組件傳值(父子組件也可以使用bus總線,但他使用自身的this.$emit\this.$on,更方便,相當於bus總線的變種)
//在main.js中引入bus,方便在全局使用:
1.2、接下來就可以在組件A和組件B中使用
//組件A接受組件B傳遞來的數據 created() { this.bus.$on("hello", (data) => { console.log(data); }); },
//組件B傳遞
<template> <button @click="handle">傳遞參數</button> </template> <script> export default{ methods:{ handle(){ this.bus.$emit("hello", { obj: 123 }); } } } </script>
2、路由傳參:
1、命名路由傳參 this.$router.push({ name: 'user', params: { user: 'nickname' }}); //頁面接受 this.$route.params 2、查詢參數傳參 this.$router.push({path: '/user', query: {user: "nickname"}}); //頁面接受 this.$route.query
3、父子組件傳參
//子組件 this.$emit("update",123); //父組件觸發 <children @update="update" /> //children代表子組件 export default{ methods:{ update(data){ console.log(data); } } }
4、vuex全局使用參數
//新建store.js import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { }, mutations: { }, actions: { }, modules: { } }) //main.js中引入,就可以全局使用state import store from './store' new Vue({ store, render: h => h(App) }).$mount('#app');