我是 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
提前致谢。
您的代码中有一些错误
this不会绑定到您的实例。computed:{
calculateSubtotal() {
let subtotal;
-----some code--------
this.subtotal = subtotal;
}
}
Run Code Online (Sandbox Code Playgroud)
computed方法不应该有副作用。这意味着您必须根据data外部信息计算值,但不要从方法内更新数据。你应该返回你想要的值。computed:{
calculateSubtotal() {
let subtotal;
-----some code--------
return subtotal;
}
}
Run Code Online (Sandbox Code Playgroud)
computed method(调用它)它就不会执行。您不会calculateSubtotal在任何地方调用,因此它永远不会运行。你需要在某个地方调用它。以模板为例。{{{calculateSubtotal}}
Run Code Online (Sandbox Code Playgroud)
这是一个适当的示例this,返回一个值并调用计算方法。但你不应该这样做。这让我想到了第四点。
methods。这是一个完整的例子
| 归档时间: |
|
| 查看次数: |
2893 次 |
| 最近记录: |