是否可以使用计算属性来计算Vue中的其他属性? [英] Is it possible to use the computed properties to compute another properties in Vue?

查看:89
本文介绍了是否可以使用计算属性来计算Vue中的其他属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I have a two computed properties like this,

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

我如何使用 id 计算 hasId 喜欢这个伪代码?

how can I use id to compute hasId like this pseudo-code?

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


推荐答案

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

You need to use correct scope to access a vue computed property.

因为你只使用 id ,它将在全局范围内搜索它并没有找到它并将返回undefined。要获得vue计算属性,您需要执行: this.id ,因此您的代码如下所示:

as you are using just id, it will search it in global scope and not find it and will return undefined. For getting vue computed property, you need to do: this.id, so your code will look like following:

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

在组件内部, this 是指我们的 Vue实例。但是你可以从这个访问$ route和其他类似函数,因为它们在 Vue.prototype 中定义,见下文来自 vue-router 的代码:

Inside a component, this refers to our Vue instance. However you can access $route and other similar function from this, as they are defined at Vue.prototype, see below code from vue-router:

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

这篇关于是否可以使用计算属性来计算Vue中的其他属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆