gpt4 book ai didi

javascript - Vue 3 : Add global method via Plugin not working

转载 作者:行者123 更新时间:2023-12-05 00:33:39 25 4
gpt4 key购买 nike

我正在尝试构建一种可以在任何模板中使用的方法来自动构建本地镜像 url。
我面临的问题是,当我尝试构建一个添加全局属性的插件时,它不起作用!
插件代码

// src/plugins/urlbuilder.js
export default {
install: (app) => {
app.config.globalProperties.buildImageUrl = imageName => require('@/assets/images/' + imageName);
}
}
Main.js 文件
// 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')
我渲染图像的主视图
// src/views/Home.vue
<template>
<img :src="buildImageUrl('myimage.jpg')">
</template>
我在我的开发控制台中收到此错误:
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)
注:这在我添加纯粹的全局属性时有效,但我读到最好的方法是通过插件。
当我这样做时它有效:
app = createApp(App)

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

app.use(router).mount('#app')
我究竟做错了什么?

最佳答案

更好的方法是使用提供和注入(inject)

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

app.provide('$urlbuilder', urlbuilder);
阅读更多关于 provide and inject

关于javascript - Vue 3 : Add global method via Plugin not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68923182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com