Vuex实现数据共享

Vuex是什么

弄明白这张图,vuex也就会使用了。vuex指的是整个虚线部分的内容,当我们的一个项目之中,各个页面,多个组件之间数据传值很困难的时候,我们可以这样去想,如果我们把这些公用的数据,放到一个公共的存储空间去存储,然后呢,某一个组件改变了这个公共的数据,其他的组件也能感知到。

右侧虚线的区域就是公共存储的区域,可以理解成一个store仓库,这个所有的公共数据都存放在state之中,某一个组件想调用公共数据,直接调用state就可以了。

组件有的时候想改变state的数据,怎么改变呢,要走一个流程,组件调用Actions(异步处理或者批量的同步操作)-->mutations(改变公共的值,也可以跳过Actions)

一,安装

  • npm install vuex --save

二,引入vue使用vuex

在src目录下,创建一个store目录,在store文件夹创建一个index.js

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

Vue.use(Vuex)
// Vue使用插件都是用Vue.use()

export default new Vuex.Store({
  state: {
    city: '深圳'
  }
})

在main.js使用

import store from './store'
//会自动找index

new Vue({
  el: '#app',
  router,
  store: store,
  components: { App },
  template: '<App/>'
})

在组件中,比如首页

<div class="header-right">
          {{this.$store.state.city}}
</div>

三,父组件之间传值,中转

<div class="area"
        v-for="(item, key) of cities"
        :key="key"
        :ref="key"
        @click="handleCityClick(item.name)"
      >


 methods: {
    handleCityClick (city) {
      this.$store.dispatch('changeCity',city)
    //可以省列上面的dispatch,用commit直接调用
mutation,省了actions
this.$store.commit('changeCity',city)
    //路由跳转
    this.$router.push('/')
    }
  }



//在store文件夹下的index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    city: '深圳'
  },
  actions: {
    changeCity (ctx, city) {
      ctx.commit('changeCity', city)
    }
  },
  mutations: {
    changeCity (state, city) {
      state.city = city
    }
  }
})
原文地址:https://www.cnblogs.com/hechunfeng/p/13882374.html