如何从Vue 2中的另一个数据变量引用数据变量? [英] How to reference data variable from another data variable in Vue 2?

查看:16
本文介绍了如何从Vue 2中的另一个数据变量引用数据变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 vue 数据中有这个:

I have this in vue data:

data() {
    return {

      names: [],
      length: names.length,
}

但这不起作用,因为引发了 RefereneError ( names is undefined ).我使用了 this.names 但没有任何区别.

But this does not work as RefereneError ( names is undefined ) is thrown. I used this.names but makes no difference.

推荐答案

你需要做这样的事情才能让它工作:

You need to do something like this to make it work:

#第一种方式

data() {
    let defaultNames = [];
    return {
      names: defaultNames,
      length: defaultNames.length
    }
}

#2nd 方法——使用计算数据(更好的方法):

#2nd way — using computed data (the better way):

data() {
    return {
      names: [],
    }
},
computed: {
    length() {
        return this.names.length;
    }
}

这篇关于如何从Vue 2中的另一个数据变量引用数据变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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