如何更新Vuejs中的数据属性值?

Osm*_*afi 1 vue.js vuejs2

我是 Vuejs 新手,对 vue 反应系统仍然不太清楚。在下面的代码中,我尝试使用方法更新数据属性中变量的初始值。

<script>
  name: "OrderDetails",
  data(){
    tax:5,
    subtotal:0
  },

  computed:{
    calculateSubtotal:()=> {
      let subtotal;

      -----some code--------

      this.subtotal = subtotal;
    }
  }
</script>
Run Code Online (Sandbox Code Playgroud)

但小计仍然为 0。如何更新该值?这是代码片段https://codesandbox.io/s/affectionate-borg-384rl?file=/src/App.vue

提前致谢。

Rad*_*iță 5

您的代码中有一些错误

  1. 声明计算方法时不得使用粗箭头。this不会绑定到您的实例。
computed:{
  calculateSubtotal() {
      let subtotal;

      -----some code--------

   this.subtotal = subtotal;
  }
}
Run Code Online (Sandbox Code Playgroud)
  1. 你的computed方法不应该有副作用。这意味着您必须根据data外部信息计算值,但不要从方法内更新数据。你应该返回你想要的值。
computed:{
  calculateSubtotal() {
    let subtotal;

      -----some code--------

    return subtotal;
  }
}
Run Code Online (Sandbox Code Playgroud)
  1. 如果您从不引用computed method(调用它)它就不会执行。您不会calculateSubtotal在任何地方调用,因此它永远不会运行。你需要在某个地方调用它。以模板为例。
{{{calculateSubtotal}}
Run Code Online (Sandbox Code Playgroud)

这是一个适当的示例this,返回一个值并调用计算方法。但你不应该这样做。这让我想到了第四点。

  1. 您应该只将计算方法用作任何其他数据,而不是将其作为参数传递给其他方法。这也适用于methods

这是一个完整的例子