• 从零开始学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

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

  • 相关阅读:
    计蒜客模拟赛D2T2 蒜头君的排序:区间逆序对(移动端点) + 树状数组
    计蒜客模拟赛D2T1 蒜头君的兔子:矩阵快速幂
    计蒜客模拟赛D1T2 蒜头君的树:树上节点之间最短距离和
    计蒜客模拟赛D1T1 蒜头君打地鼠:矩阵旋转+二维前缀和
    Cubieboard安装系统
    awk速查手册
    sed速查手册
    常用正则表达
    MySQL索引小记
    jQuery中attr和prop的区别
  • 原文地址:https://www.cnblogs.com/flower-dance/p/14944650.html
Copyright © 2020-2023  润新知