非父子组件间传值(二)

时间:2020-03-04 14:23:45   收藏:0   阅读:70

上回通过总线机制实现了非父子组件间的传值,这篇随笔将使用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) {}
    }
  }
})

  

 

原文:https://www.cnblogs.com/lora404/p/12408736.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!