【问题标题】:VueJS get computed properties dynamicallyVueJS 动态获取计算属性
【发布时间】:2021-01-13 04:23:51
【问题描述】:

我需要计算以calculateSum 字符串开头的computed 属性的总和。

我不知道该怎么做,因为我无法使用 this.computed 获取他们的名字

所以我的方法/尝试是:

getSubTotal(){
    var computed_names = [];
    var computed_names_filtered = computed_names.filter(x => {return x.startsWith('calculateSum')})
    return _.sum(computed_names_filtered.map(x => eval(x+'()'))
}

你知道怎么做吗?

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component


    【解决方案1】:

    也许这可以帮助您获得计算列表:

    this.$options.computed
    

    【讨论】:

      【解决方案2】:

      您可以使用this['computed_name'] 使用bracket accessor 动态访问它们 因为组件实例是一个对象:

      var computed_names = Object.keys(this);
      var computed_names_filtered = 
      computed_names.filter(x => {return x.startsWith('calculateSum')})
       _.sum(computed_names_filtered.map(x => this[x]))
      

      请注意,计算属性是在没有() 的情况下调用的,但如果你想调用一个方法,你可以使用this['method_name']()

      例子:

      // ignore the following two lines, they just disable warnings in "Run code snippet"
      Vue.config.devtools = false;
      Vue.config.productionTip = false;
      
      new Vue({
        el: '#app',
        computed: {
          op1() {
            return 1;
          },
          op2() {
            return 2;
          },
          op3() {
            return 23;
          },
          total() {
            return ['op1', 'op2', 'op3'].map(o => this[o]).reduce((acc, curr) => acc += curr, 0)
      
          }
        },
         
      })
      <link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
      <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
      
      
      <div id="app" class="container">
        {{total}}
      </div>

      【讨论】:

        猜你喜欢
        • 2020-02-05
        • 2018-02-21
        • 2017-08-23
        • 2018-01-02
        • 2021-01-14
        • 2019-02-11
        • 1970-01-01
        • 2018-03-26
        • 2018-10-05
        相关资源
        最近更新 更多