【问题标题】:Is it possible to use the computed properties to compute another properties in Vue?是否可以使用计算的属性来计算 Vue 中的另一个属性?
【发布时间】:2016-12-15 21:56:35
【问题描述】:

如果我有两个这样的计算属性,

computed: {
  id: function(){ return this.$route.query.id; },
  hasId: function(){ return this.$route.query.id !== undefined; }
}

如何使用id 来计算hasId 这样的伪代码?

computed: {
  id: function(){ return this.$route.query.id; },
  hasId: function(){ return id !== undefined; }
}

【问题讨论】:

  • return id -> return this.id() 解决您的问题
  • 你为什么不把它作为回复发布以便它可以被接受?
  • 因为您不能对评论投反对票,而且 OP 的问题中经常存在只能通过澄清才能知道的问题

标签: javascript vue.js


【解决方案1】:

您需要使用正确的范围来访问 vue 计算属性。

当您只使用id 时,它将在全局范围内搜索它而不找到它并返回未定义。要获取 vue 计算属性,您需要:this.id,因此您的代码将如下所示:

computed: {
  id: function () { return this.$route.query.id; },
  hasId: function () { return this.id !== undefined; }
}

在组件内部,this 指的是我们的Vue instance。但是,您可以从this 访问 $route 和其他类似功能,因为它们在Vue.prototype 中定义,请参见vue-router 的以下代码:

 Object.defineProperty(Vue.prototype, '$route', {
    get: function get$1 () { return this.$root._route }
 })

【讨论】:

  • 我不明白。如果您有时间,请查看我对@aaaaaa 其他回复的评论。根据我的理解,this.id() 应该指的是基本的 Vue 对象,而不是当前创建的组件。我确定我错过了什么,但是什么?
  • @KonradViltersten 更新了答案,如果它回答了您的问题,请告诉我。
  • this 是 javascript 中一个被滥用的结构。 Vue 真的不应该在“计算”对象等令人困惑的情况下与 this 混淆。
【解决方案2】:

您的伪代码非常接近。只需将id 更改为this.id

computed: {
  id: function(){ return this.$route.query.id; },
  hasId: function(){ return this.id !== undefined; }
}

【讨论】:

  • 我不明白它为什么起作用。根据我读过的所有内容,在这种情况下,this 指的是 Vue 对象而不是组件实例本身(这就是为什么 this.$route 可以工作,这就是我不能使用新的 JS 语法prop:()=>{...} 的原因) .我猜this.id() 也会引用根 Vue 对象中的某些属性 id... 请问我错过了什么?
  • 我不能和 vuejs 说话,但是this 指的是它拥有的属性的对象。在 hasId 的情况下,this 指的是computed。此外,如果您想使用新的 js 语法,那么hasId() { return this.id() !== undefined; } 将是您的最佳选择。
  • 我不认为 this.id() 作为函数调用是正确的
  • 你是对的,谢谢 - 我已经使用了 vue 并且 vue 决定这些应该神奇地变成 getter 属性而不是函数,即使它们被编写为函数。我不同意设计选择,但 vue 就是这样。
【解决方案3】:

我遇到了同样的问题,我只是使用观察者解决了它。希望对您有所帮助:

 <div id="app">
  <label> true or false
   <input v-model="checkbox" type="checkbox">
  </label>   
</div>

<script>
new Vue({
    el: '#app',
    data: {
      checkbox: false,
    },

    computed: {

      checkboxComputed(){
        return this.checkbox;
      },

      lonelyComputed(){
        console.log('who bothers?');
        }
      },

    watch: {

      checkboxComputed(value){
        if(value){
          console.log('checkboxComputed is changed!')
          return this.lonelyComputed;
        }
      }
    }
});

</script>

【讨论】:

  • 我通过一个激进的举措解决了我与 Vue 的所有问题。我切换到Angular,呵呵。不知何故,它对我来说效果更好。不确定是框架还是我,所以我不是在抱怨 Vue。只是我的问题在切换后就消失了,哈哈哈。
猜你喜欢
  • 2020-05-17
  • 2020-12-01
  • 2020-02-03
  • 2018-09-20
  • 1970-01-01
  • 1970-01-01
  • 2022-06-23
  • 2021-05-04
  • 2022-11-11
相关资源
最近更新 更多