我在下面的代码中看到了如何修改列表项的类和状态,但是我不知道在何处或如何触发了total()方法。总数被添加到<span>{{total() | currency}}</span>
的标记中,但是没有单击事件或任何绑定到我的代码中的反应。
<template>
<!-- v-cloak hides any un-compiled data bindings until the Vue instance is ready. -->
<form id="main" v-cloak>
<h1>Services</h1>
<ul>
<!-- Loop through the services array, assign a click handler, and set or
remove the "active" css class if needed -->
<li
v-for="service in services"
v-bind:key="service.id"
v-on:click="toggleActive(service)"
v-bind:class="{ 'active': service.active}">
<!-- Display the name and price for every entry in the array .
Vue.js has a built in currency filter for formatting the price -->
{{service.name}} <span>{{service.price | currency}}</span>
</li>
</ul>
<div class="total">
<!-- Calculate the total price of all chosen services. Format it as currency. -->
Total: <span>{{total() | currency}}</span>
</div>
</form>
</template>
<script>
export default {
name: 'OrderForm',
data(){
return{
// Define the model properties. The view will loop
// through the services array and genreate a li
// element for every one of its items.
services: [
{
name: 'Web Development',
price: 300,
active:true
},{
name: 'Design',
price: 400,
active:false
},{
name: 'Integration',
price: 250,
active:false
},{
name: 'Training',
price: 220,
active:false
}
]
}
},
// Functions we will be using.
methods: {
toggleActive: function(s){
s.active = !s.active;
},
total: function(){
var total = 0;
this.services.forEach(function(s){
if (s.active){
total+= s.price;
}
});
return total;
}
},
filters: {
currency: function(value) {
return '$' + value.toFixed(2);
}
}
}
</script>
编辑:
工作示例
https://tutorialzine.com/2016/03/5-practical-examples-for-learning-vue-js
答案 0 :(得分:1)
因此,我相信对正在发生的事情的解释是,数据的services
对象是反应性的。由于total
方法已绑定到该方法,因此在调用toggleActive
方法时,它正在更新services
,这也会导致total
方法也被调用。
从此处的文档“ 如何跟踪更改” https://vuejs.org/v2/guide/reactivity.html
每个组件实例都有一个相应的观察者实例,该实例将在组件呈现期间“触摸”的所有属性记录为依赖项。稍后,当触发依赖项的设置器时,它会通知监视程序,从而导致组件重新呈现。
我经常发现简化正在发生的事情有助于我理解它。如果您做了上面的非常简化的版本,它可能看起来像这样。
<div id="app">
<button @click="increment">Increment by 1</button>
<p>{{total()}}</p>
</div>
new Vue({
el: "#app",
data: {
counter: 0,
},
methods: {
increment: function(){
this.counter += 1;
},
total: function(){
return this.counter;
}
}
})
工作示例:https://jsfiddle.net/skribe/yq4moz2e/10/
如果通过将数据属性counter
放在模板中进一步简化它,则当其值更改时,您自然希望模板中的值也将被更新。因此,这应该可以帮助您理解为什么调用total
方法。
<div id="app">
<button @click="increment">Increment by 1</button>
<p>{{counter}}</p>
</div>
new Vue({
el: "#app",
data: {
counter: 0,
},
methods: {
increment: function(){
this.counter += 1;
},
}
})
答案 1 :(得分:0)
更新数据时,将重新呈现组件中的模板。这意味着模板将触发所有绑定到模板的方法。您可以通过添加动态日期来查看它。
<div id="app">
<button @click="increment">Increment by 1</button>
<p>{{total()}}</p>
<p>
// Date will be updated after clicking on increment:
{{date()}}
</p>
</div>
new Vue({
el: "#app",
data: {
counter: 0,
},
methods: {
increment: function(){
this.counter += 1;
},
total: function(){
return this.counter;
},
date: function() {
return new Date();
}
}
})