Vue 3: Add global method via Plugin not working

Viewed 689

I'm trying to build a method that can be used inside any template to automatically build local image urls.

The issue I'm facing is that when I try to build a plugin that adds a global property, it's not working!

Plugin code

// src/plugins/urlbuilder.js
export default {
    install: (app) => {
        app.config.globalProperties.buildImageUrl = imageName => require('@/assets/images/' + imageName);
    }
}

Main.js file

// src/main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import urlbuilder from './plugins/urlbuilder.js'

createApp(App).use(router).use(urlbuilder).mount('#app')

Home view where I render the image

// src/views/Home.vue
<template>
    <img :src="buildImageUrl('myimage.jpg')">
</template>

and I'm getting this error in my the dev console:

Uncaught (in promise) TypeError: _ctx.buildImageUrl is not a function
    at Proxy.render (cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader-v16/dist/templateLoader.js?!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader-v16/dist/index.js?!./src/views/Home.vue?vue&type=template&id=fae5bece&scoped=true:57)
    at renderComponentRoot (runtime-core.esm-bundler.js:922)
    at ReactiveEffect.componentUpdateFn [as fn] (runtime-core.esm-bundler.js:4667)
    at ReactiveEffect.run (reactivity.esm-bundler.js:195)
    at setupRenderEffect (runtime-core.esm-bundler.js:4793)
    at mountComponent (runtime-core.esm-bundler.js:4576)
    at processComponent (runtime-core.esm-bundler.js:4534)
    at patch (runtime-core.esm-bundler.js:4138)
    at ReactiveEffect.componentUpdateFn [as fn] (runtime-core.esm-bundler.js:4744)
    at ReactiveEffect.run (reactivity.esm-bundler.js:195)

Note: This works when I add purely a global property, but I read the best way to do this was via plugin.

It works when I do this:

app = createApp(App)

app.config.globalProperties.buildImageUrl = imageName => require('@/assets/images/' + imageName)

app.use(router).mount('#app')

What am I doing wrong?

1 Answers

A better way would be to use provide and inject

import urlbuilder from './plugins/urlbuilder.js'

app.provide('$urlbuilder', urlbuilder);

Read more about provide and inject

Related