Vue项目 --- vuex

作者: V火力全开 | 来源:发表于2018-07-16 14:39 被阅读36次

什么是Vuex
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式

vuex.png

创建/src/store目录,然后在main.js中加入如下代码:

import store from './store'

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

使用例子

/src/store/index.js加入如下代码:

import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import mutations from './mutations'

Vue.use(Vuex)

export default new Vuex.Store({
  state,
  mutations,
  getters: {
    doubleCity (state) {
      return state.city + ' ' + state.city
    }
  }
})

然后我们在/src/store目录下创建state.js,mutations.js

state.js中代码:

let defaultCity = '上海'
try {
  if (localStorage.city) {
    defaultCity = localStorage.city
  }
} catch (e) {}

export default {
  city: defaultCity
}

mutations.js中代码:

export default {
  changeCity (state, city) {
    state.city = city
    try {
      localStorage.city = city
    } catch (e) {}
  }
}

在某个组件中使用映射

<div class="button">{{this.currentCity}}</div>

import {mapState, mapMutations} from 'vuex'

computed: {
    ...mapState({
      currentCity: 'city'
    })
  },
  methods: {
    handleCityClick (city) {
      this.changeCity(city)
      this.$router.push('/')
    },
    ...mapMutations(['changeCity'])
  },

相关文章

网友评论

    本文标题:Vue项目 --- vuex

    本文链接:https://www.haomeiwen.com/subject/egqbpftx.html