You are here
Home > vue

vue 动态路由 找不到路由

使用 vue-router 创建动态路由时,第一次写成了这样:

<div class="ultop" v-for="cate in categories">
      <router-link :to="{name:'/book',params:{cid: cate.id}}" :name="cate.name">{{cate.name}}</router-link>
    </div>

找遍了因内外各大平台,甚至还在油管上转了一圈,将近2个小时,确依然无解。感觉语法上来说是完全无错的,后来仔细捋了一遍,忽然想到这个 :to="name:这里是name,这里会不会和laravel里一样是个路由别名?然后找到了 router/router.js里的导入路由时的别名,改成了这样:

<div class="ultop" v-for="cate in categories">
      <router-link :to="{name:'/book',params:{cid: cate.id}}" :name="cate.name">{{cate.name}}</router-link>
    </div>

结果,不报路由错误了,却报需要cid这个参数,再看下data里定义的数据,原来是写的cid,这时也说明一个问题,如果这里cid没有参数时,写成0也可以,但不能为空。

<!-- src/components/book-cate.vue-->
<template>
  <div id="book-cate">
    <div class="ultop" v-for="cate in categories">
      <router-link :to="{name:'book',params:{cid: cate.cid}}" :name="cate.name">{{cate.name}}</router-link>
    </div>
  </div>
</template>
<script>
export default {
  name: "bookcate",
  data() {
    return {
      categories: [
        {
          path: "/book",
          name: "军事",
          cid: 1
        },
        {
          path: "/book",
          name: "历史",
          cid: 2
        },
        {
          path: "/book",
          name: "纪实文学",
          cid: 3
        }
      ]
    };
  }
};
</script>

<!-- src/components/router-view.vue -->
<template>
  <ul>
      <li v-for="i in conf">
        <router-link :to="i.path" :name="i.name">{{i.name}}</router-link>
      </li>
  </ul>
</template>
<script>
export default {
  name:"router",
  data(){
    return {
      conf:[
          {
              path:'/cate',
              name:'读书分类',
              islink:''
          },
          {
              path:'/book/0',
              name:'开篇有益',
              islink:''
          },
          {
              path:'/explorer',
              name:'寝食难忘',
              islink:''
          }

      ]
    }
  }
}
</script>
<style>
ul
{
    list-style-type:none;
    margin:0;
    padding:0;
    overflow:hidden;
  /* background: #030563; */
}
li
{
    float:left;
}
a:link,a:visited
{
    display:block;
    width:120px;
    font-weight:bold;
    color:#FFFFFF;
    background-color:rgb(26, 153, 153);
    text-align:center;
    padding:4px;
    text-decoration:none;
    text-transform:uppercase;
}
a:hover,a:active
{
    background-color:#16a870;
}

</style>

Top