目錄
簡介
vuex是一個爲vue.js應用開發的狀態管理模式
基本對象
- state:數據倉庫(類似於data)
- getters:對數據獲取之前再次編譯,(類似於computed)
- mutations:修改狀態,同步。在組件中使用:$store.commit('',params) (類似於function)
- actions:異步操作。在組件中使用:$store.dispatch('',params)
如何使用
- 下載vue-cli項目:https://www.jianshu.com/p/5e13bc2eb97c
- npm install vuex
- 在項目中新建store文件夾=>index.js文件
-
// index.js import Vue from 'vue'//引入vue import Vuex from 'vuex'//引入vuex //在Vue中使用Vuex Vue.use(Vuex) //創建Vuex實例實例 const store =new Vuex.Store({ state:{ count:1, count1:0, }, mutations:{ add(state,n=0){ return state.count+=n; }, reduce(state,n=0){ return state.count-=n } }, actions:{ addFun(context,n){ return context.commit('add',n) }, reduceFun(context,n){ return context.commit('reduce',n) } }, getters:{ gettersCount1(state){ return state.count1+=10 } } }) //導出store export default store;
//main.js import Vue from 'vue' import App from './App.vue' import store from './store' Vue.config.productionTip = false new Vue({ store, render: h => h(App), }).$mount('#app')
總結
- 如果需通過頁面某個事件改變數據時使用mutation,如果獲取前內部數據進行編譯時使用getter ↵
- vue中,只有mutation能夠改變state