vuex使用方法

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

一,安裝及引入vuexvue

  1,安裝java

npm install vuex --save

  2,新建store.jsvuex

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.jsnpm

 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>                
相關文章
相關標籤/搜索