路由完整实例代码
D:\workspace\xxx\src\main.js
import Vue from 'vue' import App from './App' import VueRouter from 'vue-router' import Apple from '@/components/Apple' import RedApple from '@/components/RedApple' import Banana from '@/components/Banana' Vue.use(VueRouter) let router = new VueRouter({ mode: 'history', routes: [ { path: '/', // redirect: Apple 错误示范 redirect: '/apple' }, { path: '/apple', component: Apple, // component: { // ViewA: Apple, // ViewB: RedApple // }, children: [ { path: 'red', component: RedApple } ] }, { path: '/banana', component: Banana } ] }) // router.beforeEach() 检查登录状态 /* eslint-disable no-new */ new Vue({ el: '#app', router, template: '<App/>', components: { App } })
D:\workspace\xxx\src\App.vue
<template> <div id="app"> <img src="./assets/logo.png"> <!-- <router-view name="ViewA"></router-view> <router-view name="ViewB"></router-view> --> <transition> <keep-alive> <router-view/> </keep-alive> </transition> <router-link to="/apple">to apple</router-link> <!-- 具名路由<router-link :to="{name: 'apple'}" tag="li">to apple</router-link> --> <router-link to="/banana">to banana</router-link> <!-- <router-link to="/apple/red">to apple red</router-link> --> </div> </template> <script> export default { name: 'App' } </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
D:\workspace\xxx\src\components\Apple.vue
<template> <div> <h1 >{{ msg }}</h1> <p>{{ this.$route.params.color }}</p> <button @click="showSize">showSize</button> <router-view/> </div> </template> <script> export default { name: 'Apple', data () { return { msg: 'I am an apple' } }, methods: { showSize () { console.log(this.$route.params) } } } </script>
D:\workspace\xxx\src\components\Banana.vue
<template> <h3 >{{ mg }}</h3> </template> <script> export default { name: 'Banana', data () { return { mg: 'I am a banana' } } } </script>
D:\workspace\xxx\src\components\RedApple.vue
<template> <div> <h1 >{{ msg }}</h1> <p>{{ this.$route.params.color }}</p> <button @click="showSize">showSize</button> <router-view/> </div> </template> <script> export default { name: 'RedApple', data () { return { msg: 'I am a red apple' } }, methods: { showSize () { console.log(this.$route.params) } } } </script>