【问题标题】:Rollup Vue 3 Dynamic img srcRollup Vue 3 动态 img src
【发布时间】:2020-11-05 00:03:10
【问题描述】:

动态 img src 由 Webpack 的 require 处理:

<img :src="require(`@/assets/${posts.img}`)" alt="">

如何在使用 Rollup 的 vite-app 上做到这一点?

【问题讨论】:

    标签: vue.js rollup


    【解决方案1】:

    你可以参考docswebpack-to-vite

    使用Vite的APIimport.meta.glob转换动态require(如require('@assets/images/' + options.src)),可以参考以下步骤

    1. 创建一个模型来保存导入的模块,使用异步方法动态导入模块并将它们更新到模型中
    // 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 })
          }
        }
      }
    })
    
    1. .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>
    

    【讨论】:

      猜你喜欢
      • 2021-05-30
      • 1970-01-01
      • 2022-10-04
      • 2018-09-15
      • 1970-01-01
      • 2021-10-14
      • 2021-02-12
      • 1970-01-01
      • 2018-10-07
      相关资源
      最近更新 更多