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>                
相关文章
相关标签/搜索