Vuejs3如何在单独的文件夹中注册自定义全局指令



我想将全局自定义指令移到一个单独的文件夹中,并从文件中导入,但在Vue3中未能做到这一点。

我得了

未捕获类型错误:无法读取未定义的属性(读取"指令"(

以下是我的文件:

main.js

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import VueGtag from 'vue-gtag'
import '@/plugins/gtag'

createApp(App)
.use(
VueGtag,
{
config: { id: process.env.VUE_APP_GOOGLE_ANALYTICS_ID },
pageTrackerTemplate(to) {
return {
page_title: to.name,
page_path: to.path,
}
},
},
router
)
.use(router)
.mount('#app')

/plugin/gtag.js

import Vue from 'vue'
import { event } from 'vue-gtag'
const track = binding => () => {
event('click', {
event_category: binding.value.category,
event_label: binding.value.label,
value: 1,
})
}
Vue.directive('track', {
beforeMount(el, binding) {
const trackFn = track(binding)
el.addEventListener('click', trackFn)
el.trackFn = trackFn
},
unmounted(el) {
el.removeEventListener('click', el.trackFn)
},
})

我知道,我的gtag.jsimport Vue from 'vue'是如此的Vuejs2,现在它应该用{createApp}导入
但我只是不知道,如何在Vuejs3中使用该指令?


编辑:感谢@Leo提供的解决方案:

插件/gtag.js

import { event } from 'vue-gtag'
const track = binding => () => {
event('click', {
event_category: binding.value.category,
event_label: binding.value.label,
value: 1,
})
}
const TrackDirective = {
beforeMount(el, binding) {
const trackFn = track(binding)
el.addEventListener('click', trackFn)
el.trackFn = trackFn
},
unmounted(el) {
el.removeEventListener('click', el.trackFn)
},
}
export default TrackDirective

main.js

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import VueGtag from 'vue-gtag'
import TrackDirective from '@/plugins/gtag'
createApp(App)
.directive('track', TrackDirective)
.use(
VueGtag,
{
config: { id: process.env.VUE_APP_GOOGLE_ANALYTICS_ID },
pageTrackerTemplate(to) {
return {
page_title: to.name,
page_path: to.path,
}
},
},
router
)
.use(router)
.mount('#app')

您需要在app变量上直接使用directive

示例如下:

gtag.js

const TrackDirective = {
beforeMount: (el, binding) => {
el.addEventListener('click', () => {
console.info('tracking')
})
}
}
export default TrackDirective

main.js

import TrackDirective from "./track";
const app = createApp(App)
app.directive('track', TrackDirective)
app.mount('#app')

某些组件

<template>
<div v-track>
click on this text
</div>
</template>

参考:https://vuejs.org/guide/reusability/custom-directives.html#introduction

相关内容

  • 没有找到相关文章

最新更新