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: '<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'])
  },
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 目录 一、项目结构的核心思想 二、项目目录结构 三、资源路径编译规则 四、index.html 五、build目录...
    科研者阅读 11,451评论 0 40
  • 1.在项目main.js中引入store,并挂载 2.建立store仓库,结构如下 3.state的理解单一状态树...
    以手画圆心阅读 3,543评论 2 7
  • ## 框架和库的区别?> 框架(framework):一套完整的软件设计架构和**解决方案**。> > 库(lib...
    Rui_bdad阅读 2,953评论 1 4
  • vuex是一个状态管理模式,通过用户的actions触发事件,然后通过mutations去更改数据(你也可以说状态...
    Ming_Hu阅读 2,036评论 3 3
  • 上一章总结了 Vuex 的框架原理,这一章我们将从 Vuex 的入口文件开始,分步骤阅读和解析源码。由于 Vuex...
    你的肖同学阅读 1,805评论 3 16