有两种方式:
- eventBus
- Vuex
1. 用eventBus
- 声明一个空的Vue模块eventBus
import Vue from 'vue'
// 定义空的vue实例,作为 eventbus实现非父子组件之间的通信(vue2.x中去掉了broadcast)
var eventBus = new Vue({});
export default eventBus;
- “医院列表页”通过eventBus.$emit传参给上一个页面
import eventBus from '../service/eventbus.js';
methods:{
//列表选中具体医院的点击事件
goback(hospital){
//传递一个map,choiceHospital是key,hospital是value
eventBus.$emit('choiceHospital',hospital);
//调用router回退页面
this.$router.go(-1);
}
}
- “首页”以及“预约”页面接收参数
import eventBus from '../service/eventbus.js';
//每次激活时
activated(){
//根据key名获取传递回来的参数,data就是map
eventBus.$on('choiceHospital', function(data){
//赋值给首页的附近医院数据模型
this.nearestOrg = data;
}.bind(this));
}
2. 用Vuex
即:子组件里,把值存到store仓库,父组件里取出。
这里简单说一下store的工作流程:
一般项目结构里新建store文件夹,里面分别新建js文件,依次为:index.js
mutations.js
getters.js
mutation-types.js
actions.js
- 组件里触发this.$store.dispatch(action里定义的方法)
- action 方法里调用commit触发mutation的方法
- mutation 方法里给state里的变量赋值
- getter 实时监听state里变量值的变化
store的使用方式有两种,一种是像上面新建几个文件,各自如上命名,各写各的。此处不表。
这里着重讲讲另一种方式,module 方式,举个栗子:
src文件夹下新建store文件夹,以及其他文件,目录结构如下:
index.js 内容如下:
import Vue from 'vue'
import Vuex from 'vuex'
import home from './modules/home'
import me from './modules/me'
Vue.use(Vuex)
export default new Vuex.Store({
// actions,
// getters,
modules: {
home,
me
},
strict: true
})
mutaiton-types.js 内容如下:
export const COUNTRY_LIST = 'COUNTRY_LIST'
export const CUST_LIST = 'CUST_LIST'
home.js 的内容如下:
import * as types from '@/store/mutation-types'
const state = {
countryList: [],
custList: []
}
const getters = {
countryList: state => {
return state.countryList
},
custList: state => {
return state.custList
}
}
const actions = {
setCountryList({ commit }, countryList) {
commit(types.COUNTRY_LIST, countryList)
},
setCustList({ commit }, custList) {
commit(types.CUST_LIST, custList)
}
}
const mutations = {
[types.COUNTRY_LIST](state, countryList) {
state.countryList = countryList
},
[types.CUST_LIST](state, custList) {
state.custList = custList
}
}
export default {
state,
getters,
actions,
mutations
}
怎么在单个组件里使用呢?
改变store的state的变量值,是这样:
this.$store.dispatch('setCountryList',res.data.countryList)
获取store里的变量的值,是这样:
let countryMap = this.$store.getters.countryList
或者 let countryMap = this.$store.state.countryList