参考代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>路由简单测试-2</title> </head> <body> <div id="app"> <router-link to="/">首页</router-link> <router-link to="/news">新闻</router-link> <router-link to="/news/2222">带参数新闻2</router-link> <router-link to="/news?userId=3333">带参数新闻3</router-link> <hr> <router-link to="news">[当前路径上/新闻1]</router-link> <router-link :to="{name:'namenews2',params:{userId:2222}}">[带参数新闻2]</router-link> <router-view></router-view> </div> <script src="../js/vue.js"></script> <script src="../node_modules/vue-router/dist/vue-router.js"></script> <script> const indexTmp = Vue.extend({ template:'<div><h2>{{msg}}</h2><button @click="routerTo">click here to news page1</button><button @click="routerTo2">click here to news page2</button><button @click="routerTo3">click here to news page3</button></div>', data() { return{ msg: 'Welcome to gCode Teacher!' } }, methods:{ routerTo(){ this.$router.push({name:'namenews',params:{userId:1111}}); }, routerTo2(){ this.$router.push({name:'namenews2',params:{userId:2222}}); }, routerTo3(){ this.$router.push({name:'namenews3',params:{userId:3333}}); } } }); const newsTmp = Vue.extend({ template: '<div>this is the news page1. params.userId is: {{this.$route.params.userId}}--query.userId is:{{this.$route.query.userId}}</div>' }); const newsTmp2 = Vue.extend({ template: '<div>this is the news page2. param.userId is: {{this.$route.params.userId}}--query.userId is:{{this.$route.query.userId}}</div>' }); const newsTmp3 = Vue.extend({ template: '<div>this is the news page3. param.userId is: {{this.$route.params.userId}}--query.userId is:{{this.$route.query.userId}}</div>' }); const index = Vue.component('index',indexTmp); const news = Vue.component('news',newsTmp); const news2 = Vue.component('news2',newsTmp2); const news3 = Vue.component('news3',newsTmp3); const router = new VueRouter({ routes: [ {path: '/',name:'namenullindex',component:index}, {path: '/index',name:'nameindex',component:index}, {path: '/news/:userId',name:'namenews2',component:news2}, {path: '/news?userId=:userId',name:'namenews3',component:news3}, {path: '/news',name:'namenews',component: news } ] }); const app = new Vue({ el: '#app', router: router }); </script> </body> </html>