
今天群里有个小伙伴问了这样的一个问题,vue中动态给img赋值,路径怎么写?相对路径和绝对路径都找不到。作为过来人,立马想到的就是,他可能没有搞懂vue中assets和static目录的区别。
在vue的目录结构中,static是静态资源目录,可以用于放置图片、字体等。而在src目录(开发目录)下,同样提供了一个assets目录,可以用于存放图片,比如logo等。虽然这两个目录都可以用于放置图片,但是在使用上却是有一些差别的。
场景一:在HTML中使用的区别
在HTML中使用,两者都可以直接使用路径来访问。
<img src="../assets/liuyanla.png" alt="liuyanla" title="assets和static目录的区别"> <img src="/static/liuyanla.png" alt="liuyanla" title="assets和static目录的区别">
要注意的是,访问assets目录下的资源文件使用的是相对路径,而访问static目录下的资源文件则需要使用绝对路径,具体原因在后面说。
场景二:在JS中使用的区别
assets下的资源如果要在js中使用的话,路径需要经过webpack中的file-loader编译,如果直接编写路径会导致加载资源失败(找不到资源)。
<template> <div> <img :src="liuyanla" title="assets和static目录的区别"> <img :src="liuyanla" title="assets和static目录的区别> </div> </template> export default { name: 'yanggb', data () { return { assetsUrl: require('../assets/yanggb.png'), staticUrl: '/static/yanggb.png' } } }
因为webpack使用的是commonJS规范,因此必须要使用require才能将模块化的静态图片资源加载进来(引用依赖)。
场景三:在打包时候的区别
在vue的组件中,所有的模板和css都会被vue-html-loader和css-loader解析,并查找资源的url,比如在<img src=”./liuyanla.png”>中,该url是相对的资源路径,就会由webpack解析为模块依赖,而因为liuyanla.png不是js,当被视为模块依赖的时候,就需要使用url-loader和file-loader来处理它。因为vue-cli的webpack脚手架中已经配置了这些loader,因此可以使用相对/模块路径来访问这些资源文件。
由于这些资源在webpack构建的过程中可能会被内联/复制/重命名,因此它们可以视作是源码的一部分,这也是为什么建议要将webpack处理的静态资源放在src中和其他的源文件放在一起的原因。事实上,这些资源文件甚至可以不必放到src/assets目录下,而是放置到每个放置组件的目录下,使用模块/组件的组织方式使用它们。
相比之下,在static下目录下面的文件是不会被webpack处理的,这些资源文件会被直接复制到最终的打包目录下面(默认是dist/static),且必须使用绝对路径来引用这些文件。这一特性是通过在config.js文件中的build.assetsPublicPath和build.assetsSubDirectory链接来确定的。
有时我们需要修改node_module目录中的源码,在插件源码修改后,打包后的文件应放在static目录。如果放在其他目录,webpack会重新打包,可能导致出现例如【did you register the component correctly? 】这样的组件报错。
总结
1.static中的文件是不会经过webpack编译的,一般建议存放一些外部第三方(公用)的静态资源文件。
2.assets因为会经过webpack编译,建议是存放一些只有组件自己使用到的静态资源。
以上就是vue中assets和static目录的区别的全部内容,欢迎交流。
I have been reading out some of your stories and i can claim nice stuff. I will definitely bookmark your site. Joelly Staford Iives
Wonderful post! We will be linking to this great content on our site. Keep up the great writing. Charmian Brien Cyrano
Hello! I understand this is somewhat off-topic but I needed to ask. Bethanne Pancho Napoleon
I love reading through a post that can make people think. Also, many thanks for allowing me to comment. Dotty Ernie Coltson
Just beneath, are several completely not associated websites to ours, even so, they may be surely really worth going over. Annamaria Tonnie Reese
Thank you ever so for you article post. Really looking forward to read more. Really Cool. Karine Langsdon Gerhardine
We came across a cool web site that you could possibly take pleasure in. Take a appear if you want. Kirstin Willi Sethrida
You made some decent points there. I looked on the internet for the problem and located most individuals will go along with along with your website. Merrily Egan Meares
This post provides clear idea for the new people of blogging, that actually how to do blogging and site-building. Leontine Dugald Richardo
Utterly indited content material , thankyou for entropy. Lorie Johnny Dwan