Vue中的方法在点击时运行两次

新手上路,请多包涵

为什么方法集会运行两次?单击星标时,您可以看到控制台。如果我删除 @click="set(rating)" 什么也没有发生,所以不像在其他地方再次调用它。

http://jsfiddle.net/q22tqoLu/

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

原文由 Ivan Topić 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 758
2 个回答

如果将 @click="set(rating)" 移动到 <input/> 而不是 <label/> ,它将运行一次。

原文由 Vad 发布,翻译遵循 CC BY-SA 3.0 许可协议

@click.stop="clickfunction($event)"

这将停止下一次调用,并且只会调用一次函数。

原文由 Rupesh Terase 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题