vuex流程簡單示例
阿新 • • 發佈:2018-11-25
在vue-cli中使用vuex(個人理解實現資料的公用):
1.安裝vuex,在vue-cli目錄下的src檔案下建立vuex目錄=》vuex資料夾下建立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 })
2,在components目錄下建立Count.vue元件,程式碼如下
<template> <p>{{$store.state.count}}</p> <p>{{count}}</p> <button @click="$store.commit(add,10)"></button> <button @click="$store.commit(reduce)"></button> <button @click="add"></button> <button @click="$reduce"></button> </template> <script> import store from "../vuex/store.js" import {mapMotutions} from 'vuex' export default{ data(){ return { msg:"學習vuex" } }, computed:count(){ return this.$store.state.count //computed:mapState(['count']) }, methods:{ mapMutations(['add','reduce']) }, store } </script>
注:除了利用computed的計算變數來實現count,還可以瞭解以下vuex的mapState()簡化變數的引用,mapMutation()簡化方法的引用,其他諸如getter以及mapGetter()等狀態的過濾使用中可以進行了解,另外action以及module等部分可以使用中理解,目前我的工作中使用對於這一塊使用較少
3,認真理解其生命週期