Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

vue.js - Using Vue Prototypes for Custom Event

I currently have something like this:

// Emit event:
<btn @click="$emit('saveJsonFile') />

// Catch event:
<Component @saveJsonFile="doSomething" />

However, I try to stay away from magic strings (events) and instead, I want to have a file with the name of events as constants.

Example:

// events.js
export const EV_SAVE_JSON_FILE = 'saveJsonFile'

And make it a global instance:

import * as EVENTS from './events.js'
Vue.prototype.$EV = EVENTS

Now I use it like this:

// Child
<btn @click="$emit($EV.EV_SAVE_JSON_FILE) />

But how to I use it on the parent? I am getting a Vue ESLint error stating that it is an invalid v-on: v:on directives dont support the modifier 'ev_save_json_file'.

// Error
<Component @[$EV.EV_SAVE_JSON_FILE]="doSomething" />

I also tried making the event constant in small caps <Component @[$ev.ev_save_json_file]="doSomething" />, but same behavior.

Help!

question from:https://stackoverflow.com/questions/65895588/using-vue-prototypes-for-custom-event

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I don't think vue template can interpret dynamic v-on:xxx directive. However, you can achieve the same effect by using generic v-on directive to achieve what you described. Details here:

https://github.com/vuejs/vue/issues/4703

So these are the same:

<sample-component v-on:click="someHandler" />
<sample-component v-on="{ click: someHandler }" />

Back to your problem, your component can be rewritten like this:

<Component v-on="{ [$EV.EV_SAVE_JSON_FILE]: doSomething }" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...