VueJS-条件组件鼠标事件



Vue和框架的新手,我的想法可能不太"像Vue"。

试图制作一个"超级"按钮组件,该组件使用一个道具来指示按钮的行为,所以我只需要维护一个按钮组件。实现时的理想形式是这样的。。。

<super-button isType="string"></super-button>

模板是…

<button class="buttonLow" v-bind:class="{buttonHigh: isSelected}">
<slot></slot>
</button>

其中isType道具可以是momentarymomentary-multitoggletoggle-multi

我有一组基本的事件发射器/方法和监听器,它们在不考虑isType的情况下工作,只需使用另一个道具isSelected使按钮处于高或低/打开或关闭状态。

问题是试图根据isType有条件地设置鼠标事件。在弄清楚逻辑的同时,我使用了@语法来设置鼠标事件@click@mousedown@mouseup等,一切都很顺利。例如,测试期间momentary按钮的事件如下。。。

<button @mousedown="emitButtonHigh()" @mouseup="emitButtonLow" @mouseleave="emitButonLow"></button>

然而,一个简单的切换按钮看起来更像这样。。。

<button @click="emitButtonToggle()"></button>

显然,那里有点冲突。

我尝试的解决方法是在created()中使用switch语句,该语句将isType作为表达式,并有条件地注册适当的鼠标事件。。。

created(){
switch(this.isType){
case ("momentary"):{
//attach on events
break;
}
case ("toggle"):{
//attach on events
break;
}
case ("toggle-multi"):{
//attach on events
break;
}
default:{
break;
}
}
}

当switch本身工作时,我不知道如何在这个上下文中附加鼠标事件。我可以附加自定义事件,使用。。。

this.$root.$on('my-custom-event', ()=>{
//do stuff
});

但是试着做一些像。。。

this.$root.$on('click', ()=>{
//do stuff
});

或者。。。

this.$on('click', ()=>{
//do stuff
});

不起作用,我也无法找到任何方法来编写它,以创建与@click相同的功能,更不用说@mousedown@mouseup或其他内置事件了。

TL;DR

如何使用$on语法为内置事件(点击、鼠标向下、鼠标向上等)编写@语法或v-on语法,从而使事件真正启动?

您可以将所有这些组件事件附加到单个处理程序上,在触发event.type时确定它们,并从这里发出自定义事件,同时可选地传递其他参数。

const SuperButton = Vue.extend({
template: `
<button 
@mousedown="emitCustomEvent" 
@mouseup="emitCustomEvent" 
@mouseleave="emitCustomEvent">
<slot></slot>
</button>
`, 
props: {
isType: {
type: String,
default:
String
},

// ...
},
methods: {
emitCustomEvent(e) {
let type = e.type.substr('mouse'.length);
let args = {
type,
isSelected: type === 'down',
args: {
// Your additional args here
}
};

switch(this.isType) {
case ("momentary"):{
//attach on events
break;
}
// ...
}

// Or emit events regardless of the "isType"

this.$emit(`mouse:${type}`, args);
this.$emit('mouse', args);
}
}
});
new Vue({
el: '#app',
methods: {
mousing(args) {
console.log(`mouse:${args.type} from component.`);
},

mouseLeaving() {
console.log('Mouse leaving.');
}
},
components: {
SuperButton
}
});
Vue.config.devtools = false;
Vue.config.productionTip = false;
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<super-button @mouse="mousing">Super button</super-button>

<super-button @mouse:leave="mouseLeaving">Super button 2, detecting leaving only</super-button>
</div>

最新更新