Iva*_*pić 6 javascript vue.js vuejs2
为什么方法集会运行两次?单击星标时可以看到控制台.如果我删除@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>
Run Code Online (Sandbox Code Playgroud)
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'
});
Run Code Online (Sandbox Code Playgroud)
代码是基于某人的旧版本,在这里它也加倍https://codepen.io/sktwentysix/pen/oZwXjN
Vad*_*Vad 12
如果您移动@click="set(rating)"到<input/>而不是<label/>,它将运行一次.
这是浏览器的默认行为。点击<label>将触发 2 次点击,一次为<label>,一次为<input>。
避免这种情况的方法是添加@click.prevent到您的<label>标签中。
就我而言,我使用prevent@click 和 @submit 来避免冒泡。
@click.prevent="action"
@submit.prevent="action"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5778 次 |
| 最近记录: |