繁体   English   中英

Vue.js 属性从事件仅触发一次的更改

[英]Change in Vue.js property from event only firing once

我有以下 HTML:

<!DOCTYPE html>
<html>

<head>
    <script src="vue.js"></script>
</head>

<body>
    <div id="app">
        <input type="checkbox" :checked="bool" @change="checked(this)">
    </div>
    <script>
        var app = new Vue({
            el: "#app",
            data() {
                return { "bool": true }
            },
            methods: {
                checked(elem) {
                    console.log("Hey!");
                    // Cast to bool
                    this.bool = !!elem.checked;
                }
            }
        })
    </script>
</body>

我计划实现一些更复杂的行为,所以我没有使用v-model

当我单击该复选框时,每次都会记录控制台消息。 但是, bool属性仅在我第一次单击时更改,而在后续单击时不会更改。 知道出了什么问题吗?

当您尝试添加两个时!! 它只是相互移除,什么也没有发生

所以你可以简单地说

this.bool = !this.bool

会是这样

methods: {
  checked(elem) {
     console.log("Hey!");
     this.bool = !this.bool;
   }
}

问题是您正在立即调用事件处理程序: @change="checked(this)" 如果您需要访问该event请执行以下操作:

模板:

<div id="app">
   <input type="checkbox" :checked="bool" @change="checked('Args', $event)">
</div>

方法:

methods: {
  checked(arg, event) {
    console.log(arg);
    this.bool = !!event.target.checked;
  }
}

如果您不需要访问该事件 - 您可以像这样简单使用:

<div id="app">
   <input type="checkbox" :checked="bool" @change="bool = !bool">
</div>

抱歉,是我的错。 this不是引发事件的元素,而是全局窗口对象。 您可以像这样使用event.target接收元素:

<input type="checkbox" :checked="bool" @change="checked('Hi!', $event)" id="check">
this.bool = !!event.target.checked;

https://forum.vuejs.org/t/change-in-vue-js-property-from-event-only-firing-once/88105/2

感谢@an_parubets 帮助发现这个答案!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM