Vuejs3 将计算字段组合在一起

Vuejs3 combine computed field together

我正在尝试在 Vue3 中重用计算字段:

export default {
  props: ["value", "target"],
  data() {
    return {
      visible: false,
      value: 25,
      target: 100,
      colored: "green",
      achieve:0,
    };
  },
  computed: {
    achieve: function () {
      return parseFloat(((this.value / this.target) * 100).toFixed(2));
    },
    colored: function(){
        if (achieve > 95){
            colored="green";
          } else if (achieve>85){
            colored="yellow";
          } else {colored="red";}
    }
  },
};

控制台显示未定义实现。我怎样才能在另一个计算值中重新使用这个计算值?

您的代码存在几个问题。

首先,您不应该为数据属性和计算属性使用相同的名称,因为您的计算属性将被忽略,您将在控制台中收到警告。

在这种情况下你完全需要数据属性,它应该是这样的:

  data() {
    return {
      visible: false,
      value: 25,
      target: 100,
    };
  },

第二个问题是您计算的 属性 不是 return 值。 您的彩色计算 属性 应如下所示:

    colored: function(){
        if (this.achieve > 95){
            return "green";
          } else if (this.achieve > 85){
            return "yellow";
          } else {
            return "red";
        }
    }

由于您在彩色计算 属性 中访问 achieve computed 属性 您需要在访问它时使用 this. 这就是为什么您会收到 achieve is not defined 错误在控制台中。