我有一个Vue计数器,它的计数从1到10。它是作为组件实现的。我需要从主应用程序重置计数器。最好的方法是什么?从我的示例中可以看到,watch方法无法完成工作:
Vue.component('my-counter', {
template: "#counter-vue",
data: function() {
return {
age_now: null
}
},
props: {
age: Number
},
mounted: function() {
this.age_now = this.age;
TweenLite.to(this, 10, { age_now: this.$root.age_end, roundProps: "age_now", ease:Linear.easeNone });
},
watch: {
age(val) {
this.age_now = val;
}
}
});
var app = new Vue({
el: '.container',
data: {
age: 1,
age_end: 10
},
methods: {
reset() {
this.age = 1;
}
}
});
<script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/1.19.0/TweenMax.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
<script type="text/x-template" id="counter-vue">
<div>
<p>Age: {{age_now}}</p>
</div>
</script>
<div class="container">
<h1>Vue Component Reset</h1>
<my-counter :age="age"></my-counter>
<button @click.prevent="reset">Reset</button>
<p>What's the best way to implement the reset of the component to restart the count up from 1 to 10?</p>
</div>
另请参见CodePen:https://codepen.io/MSCAU/pen/OagMJy
答案 0 :(得分:2)
首先,dotnet run --urls "http://0.0.0.0:5000"
组件中的age
观察者不会触发,因为您从未更改my-counter
道具的值。如果将其初始化为age
并在点击处理程序中将其设置为1
,它将不会触发观察程序,因为该值没有改变。
但首先,在这种情况下,将1
方法移至reset
组件,然后通过{{1 }},就像这样:
my-counter
如果您希望计数器再次增加,则似乎还需要再次调用ref
方法。因此,最好将该逻辑放入可以从<my-counter ref="counter" :age="age"></my-counter>
<button @click.prevent="$refs.counter.reset">Reset</button>
钩子和TweenLite.to
方法调用的自己的方法中(例如count
)。
此外,我注意到mounted
方法似乎正在覆盖reset
道具的绑定,直到计数器完成递增。如果要在TweenLite.to
方法完成之前重置计数器,则需要存储对返回的补间对象的引用,然后在计数器启动之前调用其age
方法。
最后,我看到您在传递给TweenLite.to
的对象中引用kill
。除极少数情况外,这被认为是不好的做法,因为现在该组件不必要地依赖于始终具有this.$root.age_end
属性的根Vue实例,并且使数据流变得模糊。由于该值似乎是静态的,因此您应该将其设置为组件的data属性。或者至少将其作为道具从父母那里传入。
这是一个可行的示例,其中包含我建议的更改:
TweenLite.to
age_end