I have been working on creating a method that can generate local image URLs to be used in any template automatically.
However, I encountered an issue while trying to develop a plugin that adds a global property.
Plugin Implementation:
// src/plugins/urlbuilder.js
export default {
install: (app) => {
app.config.globalProperties.buildImageUrl = imageName => require('@/assets/images/' + imageName);
}
}
Main.js Configuration:
// 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 – Image Rendering:
// src/views/Home.vue
<template>
<img :src="buildImageUrl('myimage.jpg')">
</template>
Unfortunately, when attempting to render the image, I encountered the following error in the 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)
...
Note: While it works by directly adding a global property without using a plugin, I have read that the recommended approach is to use a plugin.
In conclusion, the manual setup below works successfully:
app = createApp(App)
app.config.globalProperties.buildImageUrl = imageName => require('@/assets/images/' + imageName)
app.use(router).mount('#app')
What could potentially be going wrong with my current implementation?