Vue 中的方法点击运行两次 [英] The method in Vue runs twice on click
问题描述
为什么方法集会运行两次?单击星标时可以看到控制台.如果我删除 @click="set(rating)"
没有任何反应,所以不会像在其他地方再次调用它一样.
HTML
<star-rating value="0"></star-rating><template id="template-star-rating"><div class="star-rating"><标签班级=星级评分__星"v-for="评分中的评分":class="{'is-selected': ((value >= rating) && value != null), 'is-disabled': disabled}"@mouseover="star_over(评级)"@mouseout="star_out"@click="设置(评级)"><输入class="星级星级星级__checkbox"类型=收音机":name="姓名":disabled="禁用":id="id":required="需要"v-model="值">★标签>
</模板>
JS
'使用严格';Vue.component('星级', {模板:'#template-star-rating',数据:函数数据(){返回 {值:空,临时值:空,评分: [1, 2, 3, 4, 5]};},道具: {'名称':字符串,'值':空,'id':字符串,'禁用':布尔值,'必需':布尔值},方法: {star_over: 函数 star_over(index) {如果(this.disabled){返回;}this.temp_value = this.value;this.value = 索引;},star_out: 函数 star_out() {如果(this.disabled){返回;}this.value = this.temp_value;},设置:函数设置(值){如果(this.disabled){返回;}//这会运行两次控制台日志(值);this.temp_value = 值;this.value = 值;}}});新的 Vue({el: '#star-app'});
该代码基于某人的旧版本,这里也加倍了 https://codepen.io/sktwentysix/pen/oZwXjN
如果将 @click="set(rating)"
移动到 而不是
,它将运行一次.
Why does the method set runs twice? You can see the console when you click the star.
If I remove @click="set(rating)"
nothing happens so not like it is again called elsewhere.
HTML
<div id="star-app" v-cloak>
<star-rating value="0"></star-rating>
</div>
<template id="template-star-rating">
<div class="star-rating">
<label
class="star-rating__star"
v-for="rating in ratings"
:class="{'is-selected': ((value >= rating) && value != null), 'is-disabled': disabled}"
@mouseover="star_over(rating)"
@mouseout="star_out"
@click="set(rating)">
<input
class="star-rating star-rating__checkbox"
type="radio"
:name="name"
:disabled="disabled"
:id="id"
:required="required"
v-model="value">
★
</label>
</div>
</template>
JS
'use strict';
Vue.component('star-rating', {
template: '#template-star-rating',
data: function data() {
return {
value: null,
temp_value: null,
ratings: [1, 2, 3, 4, 5]
};
},
props: {
'name': String,
'value': null,
'id': String,
'disabled': Boolean,
'required': Boolean
},
methods: {
star_over: function star_over(index) {
if (this.disabled) {
return;
}
this.temp_value = this.value;
this.value = index;
},
star_out: function star_out() {
if (this.disabled) {
return;
}
this.value = this.temp_value;
},
set: function set(value) {
if (this.disabled) {
return;
}
// This runs twice
console.log(value);
this.temp_value = value;
this.value = value;
}
}
});
new Vue({
el: '#star-app'
});
The code is based on older version from someone, here it also doubles https://codepen.io/sktwentysix/pen/oZwXjN
If you move @click="set(rating)"
to <input/>
instead of <label/>
, it will run once.
这篇关于Vue 中的方法点击运行两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!