非父子组件间传值(二)

上回通过总线机制实现了非父子组件间的传值,这篇随笔将使用vue的生态机制vuex实现数据共享。

这是官方文档中的图片:

state存储的是数据本身,在所有组件中都可以通过$store.state.data访问;

this.dispatch('event', data)调用actions,在actions中定义event(ctx, data)方法,在其中使用ctx.commit('event2', data)异步触发mutations;

而在mutations中定义event2(state, data)方法同步更改数据。

  methods: {
    handleCity (city) {
      this.$store.dispatch('changeCity', city)
    }
  }

  

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

Vue.use(Vuex)

let defaultCity = '云南'
try {
  if (localStorage.city) {
    defaultCity = localStorage.city
  }
} catch (e) {}

export default new Vuex.Store({
  state: {
    city: defaultCity
  },
  actions: {
    changeCity (ctx, city) {
      ctx.commit('changeCity', city)
    }
  },
  mutations: {
    changeCity (state, city) {
      state.city = city
      console.log(state.city)
      try {
        localStorage.city = city
      } catch (e) {}
    }
  }
})

  

猜你喜欢

转载自www.cnblogs.com/lora404/p/12408736.html