[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