路由配置错误,需要指定路径
P粉113938880
P粉113938880 2023-08-28 18:32:26
0
1
472
<p>我想要添加动态路由并在所有动态路由中使用相同的组件。我尝试了以下代码来渲染组件,但是我得到了一个错误,错误信息如下:</p> <blockquote> <p>[vue-router] “path”在路由配置中是必需的。</p> </blockquote> <p>添加动态路由并显示相同组件的正确方法是什么?</p> <p> <pre class="brush:js;toolbar:false;">const Foo = { template: '<div>Foo</div>' } const Home = { template: '<div>Home</div>' } const router = new VueRouter({ mode: 'history', routes: [{ path: '/', component: Home }] }) const app = new Vue({ router, el: "#vue-app", methods: { viewComponent: function(path, method) { debugger; let tf = `${path}/${method}`; let newRoute = { path: tf, name: `${path}_${method}`, components: { Foo }, } this.$router.addRoute([newRoute]) }, } });</pre> <pre class="brush:html;toolbar:false;"><script src="https://cdn.jsdelivr.net/npm/vue@2.6.14"></script> <script src="https://npmcdn.com/vue-router/dist/vue-router.js"></script> <div id="vue-app"> <a v-on:click="viewComponent('api/contact','get')">ddd</a> <router-view></router-view> </div></pre> </p>
P粉113938880
P粉113938880

全部回复(1)
P粉754473468
  1. 主要问题是你将数组传递给了addRoute函数
  2. 第二个问题是路径开头缺少了/(没有它,你将会得到一个“非嵌套路由必须包含一个前导斜杠字符”的错误)
  3. 最后使用$router.push跳转到新的路由

const Foo = {
  template: '<div>Foo</div>'
}
const Home = {
  template: '<div>Home</div>'
}

const router = new VueRouter({
  mode: 'history',
  routes: [{
    path: '/',
    component: Home
  }]
})
const app = new Vue({
  router,
  el: "#vue-app",
  methods: {
    viewComponent: function(path, method) {
      let tf = `/${path}/${method}`;

      let newRoute = {
        path: tf,
        name: `${path}_${method}`,
        component: Foo,
      }
      this.$router.addRoute(newRoute)
      this.$router.push({ name: newRoute.name })
    },
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14"></script>
<script src="https://npmcdn.com/vue-router/dist/vue-router.js"></script>

<div id="vue-app">
  <a v-on:click="viewComponent('api/contact','get')">ddd</a>

  <router-view></router-view>
</div>
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板