路由配置錯誤,需要指定路徑
P粉113938880
P粉113938880 2023-08-28 18:32:26
0
1
471
<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>
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板