如何在 Vue 3 中创建事件总线?
在 Vue 2 中,它是:
export const bus = new Vue();
Run Code Online (Sandbox Code Playgroud)
bus.$on(...)
bus.$emit(...)
Run Code Online (Sandbox Code Playgroud)
在 Vue 3 中,Vue不再是构造函数,而是Vue.createApp({});返回一个没有$on和$emit方法的对象。
我有web应用程序,其中界面基于vue.js 2.0.
我有基于select2插件显示输入的组件.
默认情况下,它会显示所选的选项,但是当用户单击它时,我会显示select2以允许用户修改选项.
代码如下所示:
<template>
<div @click="toggleEdit">
<span v-show="isEnabled">
<select
class="form-control"
:name="name"
:multiple="multiple"
>
<option v-for="opt in options" :value="opt.id"> {{ opt.text }} </option>
</select>
</span>
<span v-show="!isEnabled">
<div v-if="selectedOptions.length === 0">
{{ emptyText }}
</div>
<div v-for="opt in selectedOptions">
{{ opt }}
</div>
</span>
</div>
</template>
<script>
export default {
props: {
options: {
type: Array,
required: false,
default: function() {
return []
}
},
name: {
required: true,
type: String
},
multiple: {
required: false,
type: Boolean,
default: …Run Code Online (Sandbox Code Playgroud) 我正在尝试将 $emit 事件发送给 root,但它不起作用。当我按下回车键时,它应该发送到 root 并且组件应该获取该事件并执行将其推送到数组的函数。
JS:
Vue.component('input-comp',{
template : `
<div>
<input type="text" v-model ="textData" v-on:keyup.enter ="pushMessages"/>
<button v-on:click="pushMessages">Send text</button>
</div>`,
data : function(){
return {
textData : 'test Message'
}
},
methods : {
pushMessages : function(){
this.$root.$emit('message', { message: this.textData })
}
}
})
var vm = new Vue({
el : '#parent',
data : {
msgs : []
},
methods : {
pushMessages : function(payload){
this.msgs.push(payload.message)
}
},
updated(){
this.$root.$on('message', this.pushMessages)
}
})
Run Code Online (Sandbox Code Playgroud)
HTML:
<div id="parent">
<p …Run Code Online (Sandbox Code Playgroud)