我们如何在Vue.js中使用require.context设置延迟加载的路由,如下所示:
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const app = require.context('../views/app', false, /\.vue$/).keys()
const pub = require.context('../views/public', false, /\.vue$/).keys()
const wip = require.context('../wip', false, /\.vue$/).keys()
const routes = []
app.forEach(k => {
const key = k.replace(/(\.\/|\.vue)/g, '')
const o = {
path: `/${key}`,
name: `${key}`,
meta: { layout: 'app-shell' },
component: () => import(/* webpackChunkName: "`${key}`" */ `../views/app/${key}.vue`)
}
routes.push(o)
})
pub.forEach(k => {
const key = k.replace(/(\.\/|\.vue)/g, '')
const o = {
path: `/${key}`,
name: `${key}`,
component: () => import(/* webpackChunkName: "`${key}`" */ `../views/public/${key}.vue`)
}
routes.push(o)
})
wip.forEach(k => {
const key = k.replace(/(\.\/|\.vue)/g, '')
const o = {
path: `/${key}`,
name: `${key}`,
component: () => import(/* webpackChunkName: "`${key}`" */ `../wip/${key}.vue`)
}
routes.push(o)
})
console.log(routes)
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
路由在控制台中看起来还不错:
(20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {path: "/catalogue", name: "catalogue", meta: {…}, component: ƒ}
1: {path: "/companies", name: "companies", meta: {…}, component: ƒ}
2: {path: "/dashboard", name: "dashboard", meta: {…}, component: ƒ}
3: {path: "/inventory", name: "inventory", meta: {…}, component: ƒ}
4: {path: "/media", name: "media", meta: {…}, component: ƒ}
5: {path: "/outlets", name: "outlets", meta: {…}, component: ƒ}
6: {path: "/profile", name: "profile", meta: {…}, component: ƒ}
7: {path: "/readings", name: "readings", meta: {…}, component: ƒ}
8: {path: "/reports", name: "reports", meta: {…}, component: ƒ}
9: {path: "/sales", name: "sales", meta: {…}, component: ƒ}
10: {path: "/users", name: "users", meta: {…}, component: ƒ}
11: {path: "/about", name: "about", component: ƒ}
12: {path: "/forgot", name: "forgot", component: ƒ}
13: {path: "/home", name: "home", component: ƒ}
14: {path: "/login", name: "login", component: ƒ}
15: {path: "/demo1", name: "demo1", component: ƒ}
16: {path: "/demo2", name: "demo2", component: ƒ}
17: {path: "/demo3", name: "demo3", component: ƒ}
18: {path: "/demo4", name: "demo4", component: ƒ}
19: {path: "/test", name: "test", component: ƒ}
应用程序启动正常,但没有页面组件/内容正在加载。
您能否在代码中使用此选项解决问题:
const app = require.context('../views/app', false, /\.vue$/,'lazy').keys()
webpack选项