一般来说,Vue 和框架都是新手,我的想法可能不是很“像 Vue”。
试图制作一个带有 Prop 的“ super ”按钮组件,它决定了按钮的行为,所以我只需要维护一个按钮组件。实现时的理想形式是这样的……
<super-button isType="string"></super-button>
模板是...
<button class="buttonLow" v-bind:class="{buttonHigh: isSelected}">
<slot></slot>
</button>
在哪里isType
Prop 可以是 momentary
momentary-multi
toggle
或 toggle-multi
.
我有一组基本的事件发射器/方法和监听器,无论isType
如何工作。并使用另一个 Prop 简单地使按钮状态高或低/开或关 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
或其他内置事件。
长话短说
你怎么写出@
语法或 v-on
语法,用于内置事件(点击、鼠标按下、鼠标弹起等),使用 $on
语法,所以事件真的触发了?
最佳答案
您可以将所有这些组件事件附加到单个处理程序,确定event.type
s 因为它们被触发并从这里发出您的自定义事件,同时可选择传递其他参数。
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>
关于javascript - VueJS - 条件组件鼠标事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54564943/