vue之动态路由跳转

780 阅读1分钟

在index.js文件中配置props:true

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes = [
    {
        path: '/about/:no',
        props: true,
        name: 'About',
        component: () =>
            import ('../views/About.vue')
    },
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})
export default router

主组件App.vue中配置

<template>
  <div id="app">
    <div id="nav">
      <router-link
        :to="item.routeUrl"
        v-for="(item, index) in routeList"
        :key="index"
        >{{ item.routeName }}&nbsp;&nbsp;&nbsp;</router-link
      >
    </div>
    <button @click="addR">点此添加vip路由</button>
    <router-view />
    
  </div>
</template>

<script>
export default {
  name: "App",

  data() {
    return {
      routeList: [
        {
          routeUrl: "/",
          routeName: "Home",
        },
        {
          routeUrl: "/about/1",
          routeName: "About1",
        },
        {
          routeUrl: "/about/2",
          routeName: "About2",
        },
        {
          routeUrl: "/about/3",
          routeName: "About3",
        },
      ],
    };
  },
  
  methods: {
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

#nav {
  padding: 30px;
}

#nav a {
  font-weight: bold;
  color: #2c3e50;
  text-decoration: none;
}

#nav a.router-link-exact-active {
  color: red;
}
</style>

跳转到的About.vue组件

<template>
  <div class="about">
    <h1>动态路由 watch 监听</h1>
    <h1>{{aboutMsg}}</h1>
  </div>
</template>

<script>
export default {
  name:"About",
  props:["no"],
  data(){
    return{
      aboutMsg:"",
    }
  },
  watch:{
    $route:{
      immediate:true,
      handler:function(){
        if(this.no=='1'){
          this.aboutMsg="《雪中悍刀行》"
        }
        if(this.no=='2'){
          this.aboutMsg="《庆余年》"
        }
        if(this.no=='3'){
          this.aboutMsg="《烽火连城》"
        }
      }
    }
  }
}
</script>