[toc]
## 一览
```
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
//无异步的话,不需要actions,直接在组件commit就好
, actions: {
changeCity(ctx, city) {
// console.log('ctx',ctx)
ctx.commit('changeCity', city);
}
}
,mutations
//相当于组件中的computed属性
,getters:{
doubleCity(state){
return state.city + ' ' + state.city;
}
}
});
```
然后注入进根实例
```
new Vue({
router
, store
, render: h => h(App)
}).$mount('#app');
```
## state
```
//如果使用localStorage,最好包一层try catch,因为浏览器若关闭了localStorage或则使用隐身模式,那么就会报错
let defaultCity = '上海';
try{
if(localStorage.city){
defaultCity = localStorage.city
}
}catch(e){}
export default {
city:defaultCity
}
```
### 在组件中使用
```
,computed:{
//映射过来的属性可以改变名字
...mapState({
currentCity:'city' //将仓库中的state.city以currentCity的名字挂载到组件实例上
})
}
```
## mutation
```
export default {
changeCity(state, city) {
state.city = city;
try {
localStorage.city = city;
} catch (e) {}
}
};
```
### 组件中使用
```
import {mapState,mapMutations} from 'vuex';
...
,methods:{
handleCityClick(city){
// this.$store.commit('changeCity', city);
this.changeCity(city); //在这里使用了
this.$router.push('/');
}
,...mapMutations(['changeCity']) //将changeCity挂载到组件的实例上
}
```
- 空白目录
- vue-cli
- runtime-only
- Vue对比React
- 组件与实例
- data-binding
- computed的set和get
- scoped
- 事件
- 自定义指令
- 插件
- keep-alive
- $nextTick与生命周期
- 路由
- Vue.use(Router)
- this.$router编程式导航
- this.$route
- new Router
- routes
- mode
- linkClass
- scrollBehavior
- query
- fallback
- base
- router-view
- router-link
- 路由守卫
- 左右切换
- 滚动
- FAQ
- vuex
- 适用
- new Vuex.Store
- state
- mutations
- getters
- actions
- strict
- plugins
- modules
- namespace
- this.$store
- commit
- dispatch
- mapXX
- eventBus
- Vue工程相关
- 引用路径的简化
- css-module
- vue-loader
- 异步加载
- 支持jsx
- 让webpack支持对vuex的热替换
- .eslintrc