vuex 计数器案例
vuex 计数器案例

1、准备工作:使用vue-cli创建好一个vue项目、安装vuex
目录结构如下,因为之前使用过vue-Router所有新建过一个文件夹名字是router

使用下列命令安装vuex
npm install vuex --save
2、在src目录下新建一个文件名为store.js
内容为:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
    state: {
        count: 0
    },
    mutations: {
        increment (state) {
            state.count++
        },
        decrement(state){
            state.count--;
        }
    }
})
export default store

state对象:
1、vuex管理的状态
2、唯一的
3、state对应data,是数据源
mutations对象
1、包含多个直接更新state的方法(回调函数)的对象
2、谁来触发:action中的commit()
3、只能包含同步的代码,不能写异步代码
actions对象
1、包含多个时间回调函数的对象
2、通过执行:commit()来触发mutation的调用,间接更新state
3、谁来触发:组件中store.dispatch('action 名称')
4、可以包含异步代码(定时器,ajax)
3、在组件中加入显示数字的部分
因为方便起见,直接在App.vue里面加入了下列代码
<template>
  <div id="app">
  <div id="nav">
      <!--染成一个a标签-->
      <router-link to="/home">Home</router-link> |
      <router-link to="/about">About</router-link>
    </div>
    <!--………………前面的省略,加入以下代码-->
    <div>
      <div>计数:{{$store.state.count}}</div>
      <!--使用 $store.commit('方法名') 来触发 mutations 中的方法-->
      <button @click="$store.commit('increment')">+</button>
      <button @click="$store.commit('decrement')">-</button>
    </div>
  
  </div>
</template>
4、在main.js中导入store
import Vue from 'vue'
import App from './App.vue'
import router from './router'
//引入store
import store from './store';
Vue.config.productionTip = false
console.log(store.state.count) // -> 1
new Vue({
  router,
//加入store
  store,
  render: h => h(App)
}).$mount('#app')
5、运行
npm run serve
本案例是一个简单的vux使用例子,后续学习会继续补充
 
                    
                     
                    
                 
                    
                 
                
            
         
         
 浙公网安备 33010602011771号
浙公网安备 33010602011771号