【发布时间】:2020-11-05 00:03:10
【问题描述】:
动态 img src 由 Webpack 的 require 处理:
<img :src="require(`@/assets/${posts.img}`)" alt="">
如何在使用 Rollup 的 vite-app 上做到这一点?
【问题讨论】:
动态 img src 由 Webpack 的 require 处理:
<img :src="require(`@/assets/${posts.img}`)" alt="">
如何在使用 Rollup 的 vite-app 上做到这一点?
【问题讨论】:
你可以参考docs的webpack-to-vite:
使用Vite的APIimport.meta.glob转换动态require(如require('@assets/images/' + options.src)),可以参考以下步骤
// src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
const assets = import.meta.glob('../assets/**')
Vue.use(Vuex)
export default new Vuex.Store({
state: {
assets: {}
},
mutations: {
setAssets(state, data) {
state.assets = Object.assign({}, state.assets, data)
}
},
actions: {
async getAssets({ commit }, url) {
const getAsset = assets[url]
if (!getAsset) {
commit('setAssets', { [url]: ''})
} else {
const asset = await getAsset()
commit('setAssets', { [url]: asset.default })
}
}
}
})
.vueSFC 中使用// img1.vue
<template>
<img :src="$store.state.assets['../assets/images/' + options.src]" />
</template>
<script>
export default {
name: "img1",
props: {
options: Object
},
watch: {
'options.src': {
handler (val) {
this.$store.dispatch('getAssets', `../assets/images/${val}`)
},
immediate: true,
deep: true
}
}
}
</script>
【讨论】: