Vue项目 --- vuex

什么是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: ''
})

使用例子

/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) {}
  }
}

在某个组件中使用映射

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

你可能感兴趣的:(Vue项目 --- vuex)