首页 文章

是否可以使用计算属性来计算Vue中的其他属性?

提问于
浏览
9

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

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; }
}

2 回答

  • 8

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

    因为你只使用 id ,它将在全局范围内搜索它而不找到它并将返回undefined . 要获得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 }
     })
    
  • 0

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

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

相关问题