vuex 使用方法
阿新 • • 發佈:2017-08-04
pat stat log all 使用 exp div comm name
1、安裝vuex擴展 : npm install vuex
2、在componets目錄下新建 store.js 文件
import Vue from ‘vue‘ import Vuex from ‘vuex‘ Vue.use(Vuex) // 定義初始值 const state = { num: 0 } // 獲取變量值 const getters = { num: state => state.num } //定義觸發狀態對象方法,傳入state整個對象 //在頁面中觸發時使用this.$store.commit(‘mutationName‘) 觸發Mutations方法改變state的值 const mutations = { plus(state, num) { state.num += num; }, minus(state, num) { state.num -= num; } } //異步執行方法,傳入參數context,等同於整個store //處理Mutations中已經寫好的方法 在頁面中觸發方式是 this.$store.dispatch(actionName) const actions = { plus({commit}, num) { // 調用mutations 方法 commit(‘plus‘, num) }, minus({commit}, num) { commit(‘minus‘, num) } } export default new Vuex.Store({ state, mutations, actions, getters }) /** * 定義多個模塊 * 定義一個模塊,引入各個狀態對象或方法 */ // Const moduleA = { // state, // mutations, // getters, // actions // } /** * 引如多個模塊 */ // export default new Vuex.Store ({ // modules : { // a : moduleA //引入定義模塊 // } // })
屬性值介紹:
state:定義初始值
getters:獲取變量值
mutations: 定義觸發狀態對象方法,傳入state整個對象,在頁面中觸發時使用this.$store.commit(‘mutationName‘) 觸發Mutations方法改變state的值
actions:異步執行方法,傳入參數context,等同於整個store,處理Mutations中已經寫好的方法 在頁面中觸發方式是 this.$store.dispatch(actionName)
3、在main.js 裏添加引入store.js 代碼
// 引入sotre.js import store from ‘./components/store.js‘ new Vue({ store, // store對象 el: ‘#app‘, router, render: h => h(App) });
4、新建 TestVuex.vue
<template> <div class="testVuex"> <div>{{num}}</div> <button @click="plus">加2</button> <button @click="minus">加3</button> </div> </template> <script> import {mapGetters} from ‘vuex‘ export default { name: ‘testVuex‘, //computed 實時計算 Vue檢測到數據發生變動時就會執行對相應數據有引用的函數。 computed: { ...mapGetters([ ‘num‘ // store.js 裏定義num值 ]) }, methods:{ // 調用store.js 裏actions定義的方法 plus:function() { this.$store.dispatch(‘plus‘, 2); }, minus:function() { this.$store.dispatch(‘minus‘, 3); } }, data () { return { } } } </script>
5、效果預覽
vuex 使用方法