從零開始學VUE之VueX(抽取方法為常量形式)
阿新 • • 發佈:2021-06-28
抽取方法為常量形式
import Vue from 'vue' // 匯入vuex import Vuex from 'vuex' import {INCR} from "./type"; // 通過vue安裝vuex Vue.use(Vuex) /** * 建立store * @type {Store<{counter: number}>} */ const store = new Vuex.Store({ // 用於定義屬性 state:{ counter:1000 }, // 定義用於修改屬性的函式 mutations:{ [INCR](state){ state.counter+=100; }, // 第一個引數是 state modifyCounter(state){ state.counter--; }, // 傳遞引數 modifyCounterVal(state,val){ state.counter += val; } }, // 計算屬性也就是getters 用於獲取 getters:{ // 獲取平方 getCountPF(state) { return state.counter * state.counter; }, // 獲取 平方的2分之一getCountTwoOne(state, getters) { return getters.getCountPF / 2; }, // 獲取 平方的n分之一 引數傳遞 getCountN(state,getters){ return function (n){ return getters.getCountPF / n; } } } }) export default store
type.js
export const INCR = 'incr'
app.vue
<template> <div id="app"> <h2>訪問store</h2> <h3>{{$store.state.counter}}</h3> <!-- 通過commit傳入方法呼叫--> <button @click="$store.commit('modifyCounter')">-</button> <!-- 傳遞引數--> <button @click="$store.commit('modifyCounterVal',5)">+5</button> <!-- 常量方法--> <button @click="incr">+100</button> <h2>獲取Counter的平方</h2> <h2>{{$store.getters.getCountPF}}</h2> <h2>獲取Counter的平方 2/1</h2> <h2>{{$store.getters.getCountTwoOne}}</h2> <h2>獲取Counter的平方 n/1</h2> <h2>{{$store.getters.getCountN(5)}}</h2> </div> </template> <script> importTabBar from "./components/tabbar/TabBar"; import {INCR} from "./sotre/type"; export default { name: 'App', components:{ TabBar }, methods:{ incr(){ this.$store.commit(INCR); } } } </script> <style> @import "./assets/css/base.css"; </style>
作者:彼岸舞
時間:2021\06\28
內容關於:VUE
本文屬於作者原創,未經允許,禁止轉發