gpt4 book ai didi

javascript - 将事件绑定(bind)到多个对象

转载 作者:行者123 更新时间:2023-12-04 08:03:36 25 4
gpt4 key购买 nike

我试图将相同的行为附加到几个不同的元素上,但无法弄清楚如何。
鉴于下面的代码片段,如果您要单击按钮,两个按钮的事件会同时触发。我想知道是否可以只为单击的按钮触发事件,而无需为 button1 创建方法。和 showInside1 , ETC。

var App = new Vue({
el: '#app',
data() {
return {
showInside: false
}
},
methods:{
show: function () {
this.showInside = true
},
hide: function () {
console.log('hide')
this.showInside = false
}
},
events: {
closeEvent: function () {
console.log('close event called')
this.hide()
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
<button @click.stop="show">1 Click me</button>
<div v-if="showInside">
<p>This is box 1</p>
<button @click="hide">Close</button>
</div>


<button @click.stop="show">2 Click me</button>
<div v-if="showInside">
<p>This is box 2</p>
<button @click="hide">Close</button>
</div>
</div>

最佳答案

考虑将通用代码移至 componentslots减少重复代码并隔离数据属性:

Vue.component('my-section', {
template: `
<div class="my-section">
<button @click.stop="showInside = true">Click me</button>
<div v-if="showInside">
<slot></slot>
<button @click="showInside = false">Close</button>
</div>
</div>`,
data() {
return {
showInside: false
}
},
methods:{
show: function () {
this.showInside = true
},
hide: function () {
console.log('hide')
this.showInside = false
}
},
events: {
closeEvent: function () {
console.log('close event called')
this.hide()
}
}
})

var App = new Vue({
el: '#app',
})
.my-section {
margin: 1em;
padding: 0.5em;
border: solid 1px #ccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
<my-section>
<p>This is box 1</p>
</my-section>
<my-section>
<p>This is box 2</p>
</my-section>
</div>

关于javascript - 将事件绑定(bind)到多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66328143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com