我正在尝试将我的Vue2 2/Webpack应用程序转换为Vue3/Vite。
在Vue2 2/Webpack中,这个作品是:
<div v-html="require('!!html-loader!../../assets/icons/' + this.icon + '.svg')"></div>
Html-加载程序添加了以下内容:
"html-loader": "1.3.2",
在Vue3 3/Vite中,这会引发错误:ReferenceError: require is not defined
我已经查看过这样做的示例,但是不知道编译时文件的名称,就不知道如何做到这一点。这有可能吗?
发布于 2021-12-30 09:54:44
您还可以在来自defineAsyncComponent
的Vue3
- 参考中使用延迟加载组件技术。
或类似于import()
的@tony19 19在回答中显示
<script>
const getServiceIcon = async iconName => {
const module = await import(/* @vite-ignore */ `../assets/svg/${iconName}.svg`)
return module.default.replace(/^\/@fs/, '')
}
export default {
data() {
return {
icon: null,
iconName: 'icon1', // icon1.svg
}
},
watch: {
iconName: {
async handler(iconName) {
this.icon = await getServiceIcon(iconName)
},
immediate: true,
},
},
}
</script>
<template>
<button @click="iconName = 'icon2'">Change to another SVG</button>
<img :src="icon" height="72" width="72" />
</template>
发布于 2021-12-29 23:53:09
您可以查看vite-svg-装载机插件,并将SVG文件作为Vue组件加载。
发布于 2022-06-29 08:24:59
只需创建一个组件,就可以加载图标。这里使用复合API。
<template>
<i v-html="svg" />
</template>
<script lang="ts" setup>
import { computed } from 'vue';
const props = defineProps(['icon', 'src']);
const path = props.src ? props.src : '';
const file = `${path}icon-${props.icon}`;
const modules = import.meta.glob('../../assets/icons/**/*.svg', { as: 'raw' });
const svg = computed(() => {
return modules['../../assets/icons/' + file + '.svg'];
});
</script>
<style lang="scss" scoped></style>
这将允许您甚至使用css,顺风等样式您的SVG。
用法:
<UiIcon icon="NAME" class="w-8 fill-current text-red-500"/>
好了。
https://stackoverflow.com/questions/70523260
复制相似问题