1、首先创建一个Vue项目如下所示:
(base) jjw@jjwdeMacBook-Pro 程序 % vue create hello_world
Vue CLI v5.0.8
? Please pick a preset: Manually select features
? Check the features needed for your project: Babel, Router, Vuex
? Choose a version of Vue.js that you want to start the project with 2.x
? Use history mode for router? (Requires proper server setup for index fallback
in production) No
? Where do you prefer placing config for Babel, ESLint, etc.? In package.json
? Save this as a preset for future projects? No
Vue CLI v5.0.8
✨ Creating project in /Users/jjw/Desktop/软著/软著二/程序/hello_world.
🗃 Initializing git repository...
⚙️ Installing CLI plugins. This might take a while...
added 829 packages in 41s
🚀 Invoking generators...
📦 Installing additional dependencies...
added 7 packages in 2s
⚓ Running completion hooks...
📄 Generating README.md...
🎉 Successfully created project hello_world.
👉 Get started with the following commands:
$ cd hello_world
$ npm run serve
然后进入cd hello_world 并运行npm run serve
2、打开App.vue 将其他无用的都删除,复制下边代码即可
<template>
<div id="app">
<div v-for="(item, index) in image_list" :key="index">
<img style="width: 200px" :src="item" alt="">
</div>
</div>
</template>
<script>
export default {
data() {
return {
image_list:['/image/1.png','/image/1.png','/image/1.png']
}
}
}
</script>
3、第一种方式:在public目录下创建一个image目录,并在image目录下放上一张图片如下图所示:
保存后再打开浏览器就可以发现图片能显示出来如下图:
4、第二种方式:将public中的image文件夹复制一份放到assets目录下如图所示:标记1
将App.vue中的image_list中的图片路径改成如下形式
image_list:['./assets/image/1.png','./assets/image/1.png','./assets/image/1.png']
打开浏览器并打开调试界面后发现图片显示不出来,而且出现了报错现象
解决方法如下:在vue.config.js中添加如下内容:标记2
const { defineConfig } = require('@vue/cli-service') // 这个是创建时就存在的
const path = require('path') // 这个是需要添加的
module.exports = defineConfig({
transpileDependencies: true, // 创建时就存在
devServer: { // 下边这些都是需要添加的
open: false, //是否自动弹出浏览器页面
host: '0.0.0.0',
port: '8000',
https: false,
hot: 'only',
historyApiFallback: true,
static: { // static: ['assets']
directory: path.join(__dirname, 'src')
}
}
})