vue路径分为:

绝对路径、相对路径、~+路径 及 别名+路径

绝对路径:

(1)放在public文件夹下的内容,不会经过webpack打包处理,可以直接引用,

比如:aa.png直接放在public文件夹下,不管在哪个文件里,都可以这么引用

<img src="aa.png" style="width: 200px; height: 200px" />

(2)通过别名引用

在js中,引入带别名的文件路径,不需要在别名前加~ ,在css或者style中引入的需要在路径前面加~,路径以 ~ 开头,其后的部分将会被看作模块依赖。这意味着你可以用该特性来引用一个 Node 依赖中的资源,~相当于reqiure。

在vue.config.js中定义了别名

    chainWebpack: (config) => {

        config.resolve.alias

            .set('@', resolve('src'))  //本项目路径src路径设置别名为@

            .set('_conf', resolve('src/config')) //本项目路径src/config路径设置别名为_conf

            .set('_iconfont', resolve('src/assets/icons/iconfont'))

            .set('_css', resolve('src/assets/css/'))

            .set('_img', resolve('src/assets/img/'))

            .set('_js', resolve('src/assets/js/'))

            .set('_components', resolve('src/components'))

            .set('_header', 'src/Header')

            .set('_footer', 'src/Footer')

    }

在vue中引入js文件和css文件

注意在script中路径前面都没有~

<script>

import index from "_js/index.js";                 ==src/assets/js/index.js

import "swiper/swiper.min.css";                   ==node_modules/swiper/swiper.min.css

import "_js/vendor/swiper/swiper.min.css";  ==src/assets/js/vendor/swiper/swiper.min.css

</script>

注意style中使用别名的路径前面需要加~ 

<style scoped>

@import url(~_css/index.css);     ==src/assets/css/index.css

</style>

相对路径:

引入相对路径,路径前面需要加require

在src/view/home/index.vue中引入src/assets/img/icon-cloud-light.png
正确写法:
<img  src="require(../../assets/img/icon-cloud-light.png)" />
错误写法:
<img src="../../assets/img/icon-cloud-light.png" />
原因:除了public文件夹下的内容,其余内容都会经过webpack处理,路径就变了,所以需要用require处理一下路径

~+路径 及 别名+路径

以下示例,通过别名引入文件

通过别名设置div的背景图片
用reqiure,这样写可以
<div    class="thumbnail"
        v-bind:style=
"{backgroundImage:'url(' +require('_img/index/service-special-zone-bg-01.png') +')',}"
   >
用~,这样写不行:
<div     class="thumbnail"
         v-bind:style=
"{backgroundImage:'url(~_img/index/service-special-zone-bg-01.png)',}"
>
给div设置style样式,设置背景图片等属性
<div
        class="featurette"
        :style="[
          {
            background:
              'url(' +
              require('_img/index/service-rate-bg.png') +
              ' )  bottom center no-repeat',
          },
          {
            'background-size': 'auto 100%',
          },
          {
            'margin-bottom': '50px',
          },
        ]"
      >
</div>
通过别名引入图片
<img src="~_img/index/icon-cloud-light.png" alt="" />
通过别名引入css
<style scoped>
 @import url("~_css/index.css"); 
</style>
通过别名引入js
<script>
import index from "_js/index.js";
import Swiper from "swiper";
import "swiper/swiper.min.css"; //后跟的是swiper.css的相对路
import "_js/vendor/swiper/swiper.min.css";
</script>
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。