Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的
这个状态自管理应用包含以下几个部分:
state,驱动应用的数据源;
view,以声明方式将 state 映射到视图;
actions,响应在 view 上的用户输入导致的状态变化
安装
npm install vuex --save
引用:
(新建store文件夹,创建index.js文件,写下如下代码)
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state:{
city:'皇马'
}
})
使用
import store from './store/index'
<div class="header-right">
{{this.$store.state.city}}
</div>
例子讲解:
这是一个组件里面,想通过dispatch传参city到vuex中
(this.$store.commit(‘changeCity’,city);)通过commit也可以
methods:{
handleHotCityClick (city) {
this.$store.dispatch('changeCity',city)
alert(city)
}
},
city值先通过actions里的changeCity方法获取city参数,
再提交到mutations的changeCity 方法里,在changeCity 方法里把state.city 的值设为传过来的city值
export default new Vuex.Store({
state:{
city:'皇马'
},
actions: {
changeCity (ctx,city) {//ctx上下文参数
ctx.commit('changeCity',city)
}
},
mutations:{
changeCity (state,city) {
state.city = city
}
}
})
此时会存在几个问题:
- 选好city后,再刷新,一切又会变成默认值了
- 故而使用localStorage来进行本地存储
- 但有的浏览器不行,所以,使用localStorage一定要用trycatch
- 此时index.js文件就会变得很杂了,我们把它模块化,在store文件夹下,再建几个js文件来存放state和mutations,再在index中引入
{{this.$store.state.city}} //很冗余
可改成{{this.city}}
但要加上
import { mapState } from 'vuex'
computed:{
...mapState(['city']) //把city共用数据映射到city的计算属性中,...是展开运算符
}
vuex里的getters属性与计算属性差不多,可避免数据冗余
vuex的module,把store分隔成module
使用keep-alive优化网页性能
app.vue
<template>
<div id="app">
<keep-alive>
<router-view/>
</keep-alive>
</div>
</template>