1. 程式人生 > >20181129——Vue中兄弟元件互相傳值 Vuex非子父兄弟傳值

20181129——Vue中兄弟元件互相傳值 Vuex非子父兄弟傳值

最簡單的一個列子,可以利用子元件給父元件傳值,$emit事件,父元件接收之後再給另一個子元件進行傳值

這就是我前幾天一直在看的vuex外掛

Vue的元件通過Dispatch來呼叫action,action用於存放非同步邏輯或者少量的同步邏輯,然後Actions在commit給mutations,mutation來更改state,然後重新渲染render

新建一個store檔案,在新建一個index.js

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

Vue.use(Vuex)
export default new Vuex.Store({
	state: {
		city:'beijing'
}
})

再從main.js中import

import Store from './store/index.js'

再在根部例項新增進去

new Vue({
	store,
})

這樣每一個子元件都能用根部例項的store了
this.$store.state.city

想要改變這個store中的屬性

this.$store.dispatch('changeCity', city)

再在index.js中間新建actions這個物件

actions: {
	changeCity(ctx,city) {
		ctx.commit('changeCity', city)
}
mutations: {
	changeCity(state, city){
		state.city= city
}
}

還可以新建一個state.js 和mutations.js 然後一起匯入到index.js檔案中

import {mapState} from 'vuex'
computed : {
 ...mapState(['city'])
}

就可以在元件中直接使用city這個屬性了