[英]The method in Vue runs twice on click
为什么方法集运行两次? 单击星标时可以看到控制台。 如果我删除@click="set(rating)"
不会发生任何事情,所以不会在其他地方再次调用它。
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'
});
该代码基于某人的旧版本,在这里它也加倍了https://codepen.io/sktwentysix/pen/oZwXjN
如果您将@click="set(rating)"
到<input/>
而不是<label/>
,它将运行一次。
@click.stop="clickfunction($event)"
这将停止下一次调用并且只调用一次函数。
这是默认的浏览器行为。 点击<label>
将触发 2 次点击,一次是<label>
,另一次是<input>
。
避免这种情况的方法是将@click.prevent
添加到您的<label>
标签中。
就我而言,我使用了prevent
为 @click 和 @submit 来避免冒泡。
@click.prevent="action"
@submit.prevent="action"
如果它不影响您的程序,请将事件从click
更改为mouseup
。
@mouseup="set(rating)"
我认为您应该使用新版本的 vue。 https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js您使用的是非常旧的 0.12.16,您的问题似乎是这个旧版本的错误。 您可以在设置/JavaScript 中进行设置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.