美文网首页
vue 打包静态 img 图片路径问题

vue 打包静态 img 图片路径问题

作者: 零度的冰 | 来源:发表于2017-06-27 11:17 被阅读0次

最近在写一个后台系统项目,有一个选择功能是以图片为背景的,就想提炼出一个组件公用;但在img动态绑定的时候出现了问题,在本地运行时img是正常显示的,但build打包后就不行,img显示不;
通过分析发现build后的img是通过静态资源转码的,也就是在img的后面加上hash值,且是按需加载的,但HTML的img是动态生成的,所以在build的后的img是没有hash值的;
原代码如下:
HTML部分

    <dd>
          <div v-bind:class="[currentgame[0]['typegame'] == Active?'activeImg':'']" @click="addActive(currentgame[0]['typegame'])">
           <img :img=" '../../../../static/images/'+currentgame[0]['typegame']+'png' "  alt="">
            <p>
              <i class="fa fa-check-circle-o"></i>
            </p>
          </div>
          <span>{{currentgame[0]['name']}}</span>
     </dd>

js部分:

<script>
export default{
    data(){
        return{
      Active:'',
      activeContent:
      [
        [
            {
                "typegame": "cat",
                "name": "小猫钓鱼"
            }
    ]
  ]
</script>

这时,本地运行时没问题的,但build后报错;
对代码进行改进;
HTML部分:

      <dd>
          <div v-bind:class="[currentgame[0]['typegame'] == Active?'activeImg':'']" @click="addActive(currentgame[0]['typegame'])">
           <img :img=" currentgame[0]['img']"  alt="">
            <p>
              <i class="fa fa-check-circle-o"></i>
            </p>
          </div>
          <span>{{currentgame[0]['name']}}</span>
       </dd>

js部分,这时就需要用到 require引入文件

<script>
const cat = require('../../../../static/images/cat.png');
export default{
    data(){
        return{
      Active:'',
      activeContent:
      [
        [
            {
                "typegame": "cat",
                "name": "小猫钓鱼",
                "img":cat
            }
    ]
  ]
</script>

这时本地img将会加上hash值,img已经被引用,build后的img就是原来require时的;
主意此时的activeContent数据中增加了“img”对象,以便:img引用,如果用“typegame”则不会寻找img的url,仅仅会显示“cat”;
以上代码仅为示例部分代码;

相关文章

网友评论

      本文标题:vue 打包静态 img 图片路径问题

      本文链接:https://www.haomeiwen.com/subject/dwoscxtx.html