vuex文檔:https://vuex.vuejs.org/zh-cn/vue
vuex安裝:cnpm install vuex --savevuex
簡單使用:npm
1.新建 store/index.js異步
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex); const store = new Vuex.Store({ state:{ count:0 }, mutations: { change_count (state) { // 變動狀態 state.count++ } }, }) export default store
1.獲取屬性(寫在computed裏)this
computed:{ count(){ return this.$store.state.count } }
或spa
import {mapState} from 'vuex'
computed:mapState([ 'count' //參數和state裏面的參數同樣 ])
或文檔
import {mapState} from 'vuex'
computed:mapState({ count:state=>state.count })
狀態改變(Mutations):只作狀態變動it
change_count(){ this.$store.commit("change_count") },
或io
import { mapMutations } from 'vuex'
...mapMutations({ change_count:"change_count" //本地觸發的方法:映射的方法 })
或:function
import { mapMutations } from 'vuex'
...mapMutations([ 'change_count' ])
action方法:能夠寫邏輯代碼,異步代碼
在store/index.js
actions:{ change_count({commit,state},context){ //異步的耗時操做 setTimeout( function () { alert(state.count) commit("change_count") },100)} }
調用
change_count(){ this.$store.dispatch('change_count'); },