Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

关于vue-rouer addRoutes问题

main.js:

import Vue from 'vue'
import App from './App.vue'
import router, { initLayout } from './router'
import store from './store'

require('../mock/index')

Vue.config.productionTip = false
initLayout()
new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

router.js

export async function initLayout () {
  await axios.get('http://localhost/layout').then((res) => {
    let path = '@' + res.data[0].component
    // res.data[0].component = () => import(path)
    res.data[0].component = Promise.resolve(import(path))
    router.addRoutes([...res.data])
  })
}

mock.js

export default Mock.mock('http://localhost/layout', [{
  path: '/about',
  name: 'About',
  // route level code-splitting
  // this generates a separate chunk (about.[hash].js) for this route
  // which is lazy-loaded when the route is visited.
  component: '/views/About.vue'
}])

mock.js文件拦截了对于http://localhost/layout的请求,在main.js执行initLayout时,获取到了对应路由然后import在addRoutes。

为什么浏览器会提示 Error: Cannot find module '@/views/About.vue'

这个怎么解决啊???


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

你这写法很迷幻呀
按你的逻辑这样应该就可以了

router.js

export function initLayout () {
  return axios.get('http://localhost/layout').then((res) => {
    let path = '@' + res.data[0].component
    // res.data[0].component = () => import(path)
    res.data[0].component = Promise.resolve(import(path))
    router.addRoutes([...res.data])
  })
}

main.js

initLayout().then(() => {
    new Vue({
      router,
      store,
      render: h => h(App)
    }).$mount('#app')
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...