Vue如何动态配置img标签的图片源src

  (一)首先通过绑定数据给src提供图片地址

<template>
    <div>
        <img :src=image_path />
    </div>
</template>

<script>
export default {
   data() {
        return {
              image_path: "../assets/imgs/hello.png" // 我这里是根据图片在源码中的路径来确定的,需要依据具体的情况来赋值
       }
   }
}
</script>

  (二)通过配置文件来配置图片路径

  假设在根目录下有个static目录,在该目录下有个img文件夹,在该文件夹下有个hello.png文件,即static/img/hello.png

  同时在static/js/目录下建立一个配置文件,如:config.js文件,即static/js/config.js,其内容如下:

'use strict'

module.exports = {
     IMAGE_PATH: '/static/img/hello.png',  
}

  (三)在webpack.base.conf.js文件中保持图片名称不变

{
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[ext]')
        }
 }

  (四)在Vue文件中应用配置文件

        const configConstants = require('static/js/config.js')

        此时可以给image_path这样赋值:configConstants.IMAGE_PATH

------勉

猜你喜欢

转载自www.cnblogs.com/bien94/p/12302445.html