1. 程式人生 > >vuex使用方法

vuex使用方法

def 大型項目 很多 返回 如果 const -- 理解 ons

vuex是一個專門為vue.js設計的集中式狀態管理架構。狀態?我把它理解為在data中的屬性需要共享給其他vue組件使用的部分,就叫做狀態。簡單的說就是data中需要共用的屬性。比如:我們有幾個頁面要顯示用戶名稱和用戶等級,或者顯示用戶的地理位置。如果我們不把這些屬性設置為狀態,那每個頁面遇到後,都會到服務器進行查找計算,返回後再顯示。在中大型項目中會有很多共用的數據,所以vue給我們提供了vuex。

一,安裝及引入vuex

  1,安裝

npm install vuex --save

  2,新建store.js

import Vue from ‘vue‘
import Vuex from ‘vuex‘
Vue.use(Vuex)

const state={
    count:1
}

const mutations={
    add(state,n){
        state.count+=n;
    },
    reduce(state){
        state.count--;
    }
}

export default new Vuex.Store({
	state,mutations
})

  3,在vue模板中引用store.js

 1 <template>
 2     <div>
 3         <h2>{{msg}}</h2>
 4         <hr/>
 5         <h3>{{$store.state.count}}</h3>
 6         <div>
 7             <button @click="$store.commit(‘add‘,10)">+</button>
 8             <button @click="$store.commit(‘reduce‘)">-</button>
 9
</div> 10 </div> 11 </template> 12 <script> 13 import store from ‘@/vuex/store‘ 14 export default{ 15 data(){ 16 return{ 17 msg:‘Hello Vuex‘, 18 19 } 20 }, 21 store 22 23 } 24 </script>

vuex使用方法