从零开始学VUE之VueX(getters)

getters

相当于组件中的计算属性,用于计算state中的数据返回计算后的值的
函数的第一个参数是 state 第二个参数是 getters可以通过这个调用getters中的其他函数
如果想要传递参数 那么需要使用闭包
return funcation(参数)

定义getters

import Vue from 'vue'
// 导入vuex
import Vuex from 'vuex'

// 通过vue安装vuex
Vue.use(Vuex)

/**
 * 创建store
 * @type {Store<{counter: number}>}
 */
const store = new Vuex.Store({
  // 用于定义属性
  state:{
    counter:1000
  },
  // 定义用于修改属性的函数
  mutations:{
    // 第一个参数是 state
    modifyCounter(state){
      state.counter--;
    }
  },
  // 计算属性也就是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

调用
<template>
  <div id="app">
    <h2>访问store</h2>
    <h3>{{$store.state.counter}}</h3>
<!--    通过commit传入方法调用-->
    <button @click="$store.commit('modifyCounter')">-</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>
import TabBar from "./components/tabbar/TabBar";
export default {
  name: 'App',
  components:{
    TabBar
  }
}
</script>

<style>
@import "./assets/css/base.css";
</style>

响应式修改对象状态

Vue.set(对象|数组,key|index,value)

响应式删除对象字段

Vue.delete(对象|数组,key|index)

作者:彼岸舞

时间:2021628

内容关于:VUE

本文属于作者原创,未经允许,禁止转发

原文地址:https://www.cnblogs.com/flower-dance/p/14944650.html