1router配置
import VueRouter from "vue-router";
import HomeView from "../views/HomeView.vue";
Vue.use(VueRouter);
const routes = [
{
path: "/",
name: "root",
redirect: "/home",
},
{
path: "/home",
name: "home",
component: HomeView,
children: [
{
path: "homeChild",
name: "homeChild",
component: () => import("../components/homeChild.vue"),
},
],
},
{
path: "/about",
name: "about",
component: HomeView,
children: [
{
path: "aboutChild",
name: "aboutChild",
component: () => import("../components/aboutChild.vue"),
},
],
},
];
const router = new VueRouter({
mode: "history",
base: process.env.BASE_URL,
routes,
});
export default router;
2页面代码
<div id="app">
<nav>
<router-link to="/home">Home</router-link> |
<router-link to="/about">About</router-link> |
<router-link to="/about/container">Container</router-link>
</nav>
<img :src="'./static/1.webp'" alt="img is not show" />
<router-view />
</div>
</template>
<script>
export default {
name: "App",
data() {
return {};
},
};
</script>
<style lang="scss">
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
nav {
padding: 30px;
a {
font-weight: bold;
color: #2c3e50;
&.router-link-exact-active {
color: #42b983;
}
}
}
</style>
3vue.confg.js文件的publicPath改成 '/'
//vue.config.js
const webpack = require('webpack')
module.exports = {
publicPath: '/',
outputDir: 'com.csair.oa.newmeetingassistant', //打包文件夹
lintOnSave: true,
// transpileDependencies: true,
// assetsDir: 'static',
chainWebpack: config => {
config.module
.rule('images')
.set('parser', {
dataUrlCondition: {
maxSize: 40 * 1024 // 4KiB
}
})
},
//关闭eslint
devServer: {
disableHostCheck: true,
open: true,
// port: 81,
host: '0.0.0.0',
proxy: {
'^/proxyapi': {
target: apiHost['local'],
pathRewrite: {
'^/proxyapi': ''
},
changeOrigin: true,
},
}
}
}
1当我在home的时候,图片可以拿到
2在about的时候,图片也可以拿到
3但是在home/homeChild的时候,图片就因为路径多了一层homeChild就取不到了
4原理:在history模式并且使用 cli4是用publicPath:'./'时,访问网站根目录/home时,请求路径没有问题的,因为当前目录就是根目录/home,但当访问了/home/homeChild路由时,他的请求路径会指向当前路由对应的静态文件,比如http://lppwork.cn/home/static/js/manifest.cb27dd1efb79f9ee627b.js,但在该目录下我们没有静态文件(因为我们后端配置history所用到的connect-history-api-fallback 仍是把请求定位到一个index.html,也就是根目录的那个,这就相当于在index.html里添加了一个指向 http://lppwork.cn/memo/static/js/manifest.cb27dd1efb79f9ee627b.js的script标签,而正确的路径应该是http://lppwork.cn/static/js/manifest.cb27dd1efb79f9ee627b.js或者说是/static/js/manifest.cb27dd1efb79f9ee627b.js, 所以当然取不到资源.