vuex使用方法

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>                

 

posted @ 2018-03-06 15:35  coober  阅读(246)  评论(0编辑  收藏  举报