当前位置: 移动技术网 > IT编程>脚本编程>vue.js > vue中本地静态图片路径写法

vue中本地静态图片路径写法

2018年03月21日  | 移动技术网IT编程  | 我要评论

这里写图片描述

需求:如何components里面的index.vue怎样能把assets里面的图片拿出来。

1.在img标签里面直接写上路径:

<img src="../assets/a1.png" class="" width="100%"/>

2.利用数组保存再循环输出:

<el-carousel-item v-for="item in carouseldata" :key="item.id">
    <img :src="item.url" class="carouselimg"/>
    <span class="carouselspan">{{ item.title }}</span>
</el-carousel-item>
data: () => ({
   carouseldata:[
   {url:require('../assets/a1.png'),title:'你看我叼吗1',id:1},
   {url:require('../assets/a3.png'),title:'你看我叼吗2',id:2},
   {url:require('../assets/a4.png'),title:'你看我叼吗3',id:3}
   ]
  }),

效果如下:

index.vue里面的完整代码是这个:

<template>
 <div>  <div class=" block">
  <el-carousel class="carouselblock">
   <el-carousel-item v-for="item in carouseldata" :key="item.id">
    <img :src="item.url" class="carouselimg"/>
    <span class="carouselspan">{{ item.title }}</span>
   </el-carousel-item>
  </el-carousel>
  </div>
 <footer1></footer1>
 <img src="../assets/a1.png" class="" width="100%"/>
 </div>
</template>
<script>
  import footer1 from '../components/public/footer'
  export default {
  data: () => ({
   carouseldata:[
   {url:require('../assets/a1.png'),title:'你看我叼吗1',id:1},
   {url:require('../assets/a3.png'),title:'你看我叼吗2',id:2},
   {url:require('../assets/a4.png'),title:'你看我叼吗3',id:3}
   ]
  }),
  components:{
      footer1
    },
 }
</script>
<style lang="scss">
  @import '../style/mixin';
  .carouselblock{
    width: 100%;
    height: rem(300);
    position:relative;
    .carouselimg{
    height: rem(300);
    width:100%;
   }
   .carouselspan{
    position: absolute;
    bottom: rem(20);
    left: rem(20);
    font-size: rem(24);
    font-weight: bold;
   }
  }
  .el-carousel__container{
    width: 100%;
    height: rem(300);
  }
 .el-carousel__item h3 {
  color: #475669;
  font-size: 14px;
  opacity: 0.75;
  margin: 0;
 }
 .el-carousel__item:nth-child(2n) {
   background-color: #99a9bf;
 }
 .el-carousel__item:nth-child(2n+1) {
   background-color: #d3dce6;
 }
</style>

ps:下面看下vue.js中的图片引用路径

当我们在vue.js项目中引用图片时,关于图片路径有以下几种情形:

使用一

我们在data里面定义好图片路径

imgurl:'../assets/logo.png'

然后,在template模板里面

<<span class="hljs-title" style="box-sizing: border-box; color: rgb(0, 0, 136);">img src="
{{imgurl}}">

这样是错误的写法,我们应该用v-bind绑定图片的srcs属性

:src="imgurl">

或者

<span class="hljs-title" style="box-sizing: border-box; color: rgb(0, 0, 136);">img src="../assets/logo.png">

这种方式是按照正常html语法引用路径,放在模板里可以被webpack打包出来。

使用二

当我们需要在js代码里面写图片路径的时候,如果我们在data里面写

imgurl:'../assets/logo.png'

此时webpack只会把它当做字符串处理从而找不到图片地址,此时我们可以使用import引入图片路径:

:src="avatar" />
import avatar from '@/assets/logo.png'

在data里面定义

avatar: avatar

情形三

我们也可以把图片放在外层的static文件夹里面,然后在data里面定义:

imgurl : '../../static/logo.png'
:src="imgurl" />

以上就是我们在vue.js中引用图片路径的方式。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网