首页 > 解决方案 > Vue 方法总是被调用(不仅仅是点击)

问题描述

我对 vue 很陌生,但仍在尝试了解我的代码背后的基础知识。现在我的方法有问题。仅当用户单击按钮时才应调用它。但相反,它总是被调用。我添加了一个 alert()/console.log(),然后多次显示。

这里有一些代码:

<template>
    <div>
        <center>
            <table>
                <tr>
                    <th><button  :on-click="click(1)" class="white1"><li v-bind:class="{'icon': containertyp[1] == 'l', 'iconLH': containertyp[1] == 'lh', 'iconBH': containertyp[1] == 'bh'}"></li></button></th>
                    <th><button  :on-click="click(2)" class="white1"><li v-bind:class="{'icon': containertyp[2] == 'l', 'iconLH': containertyp[2] == 'lh', 'iconBS': containertyp[2] == 'bs'}"></li></button></th>
                    <th><button  :on-click="click(3)" class="white1"><li v-bind:class="{'icon': containertyp[3] == 'l', 'iconLH': containertyp[3] == 'lh', 'iconBS': containertyp[3] == 'bs'}"></li></button></th> 
                <tr>    
            </table>
        </center>
    </div>
</template>

export default {
    data: function () {
        return {
            nr: [],
            containertyp: [],
        }
    },
    methods: {
        click(number) {

            for (var i = 0; i < 27; i++) {
                this.nr[i] = false;
                if (number == i) {
                    this.nr[i] = true;
                }
            };
            console.log(this.nr);
            EventBus.$emit('containerclicked');

        }
    }
}

标签: javascriptvue.jsmethods

解决方案


这个属性是不同语法的奇怪混合:

:on-click="click(1)"

目前尚不清楚您是在尝试绑定onclick元素的属性还是(更有可能)向元素添加 Vue 点击侦听器。

您真正想要的很可能是这样的:

@click="click(1)"

The@是 的简写v-on:,而:原始代码中的the 是 的简写v-bind:。尝试绑定一个名为的属性on-click是完全有效的,但它将被视为自定义属性,因为on-click它实际上并不是一个东西。在渲染期间评估绑定以确定属性的值,这就是您将在渲染期间看到日志记录的原因。


推荐阅读