Vue非父子组件之间通信(单页应用)

有两种方式:

  1. eventBus
  2. Vuex

1. 用eventBus

  1. 声明一个空的Vue模块eventBus
import Vue from 'vue'

// 定义空的vue实例,作为 eventbus实现非父子组件之间的通信(vue2.x中去掉了broadcast)
var eventBus = new Vue({});
export default eventBus;
  1. “医院列表页”通过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);
    }
}
  1. “首页”以及“预约”页面接收参数
import eventBus from '../service/eventbus.js';

//每次激活时
activated(){
    //根据key名获取传递回来的参数,data就是map
    eventBus.$on('choiceHospital', function(data){
        //赋值给首页的附近医院数据模型
        this.nearestOrg = data;
    }.bind(this));
}



2. 用Vuex

Vue官方关于Vuex的文档

即:子组件里,把值存到store仓库,父组件里取出。

这里简单说一下store的工作流程:

一般项目结构里新建store文件夹,里面分别新建js文件,依次为:index.js mutations.js getters.js mutation-types.js actions.js

  1. 组件里触发this.$store.dispatch(action里定义的方法)
  2. action 方法里调用commit触发mutation的方法
  3. mutation 方法里给state里的变量赋值
  4. getter 实时监听state里变量值的变化

store的使用方式有两种,一种是像上面新建几个文件,各自如上命名,各写各的。此处不表。
这里着重讲讲另一种方式,module 方式,举个栗子:

src文件夹下新建store文件夹,以及其他文件,目录结构如下:
新建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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值