Vue router
這是一個官網的 Vue router 範例
<html> <head> <script src="https://unpkg.com/vue/dist/vue.js"></script> <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script> </head> <body> <div id="app"> <h1>Hello App!</h1> <p> <!-- use router-link component for navigation. --> <!-- specify the link by passing the `to` prop. --> <!-- `<router-link>` will be rendered as an `<a>` tag by default --> <router-link to="/onefoo">Go to Foo</router-link> <router-link to="/twobar">Go to Bar</router-link> </p> <!-- route outlet --> <!-- component matched by the route will render here --> <router-view></router-view> </div> <script> // 0. If using a module system (e.g. via vue-cli), import Vue and VueRouter // and then call `Vue.use(VueRouter)`. // 1. Define route components. // These can be imported from other files const myFoo = { template: '<div>hello foo</div>' } const myBar = { template: '<div>hello bar</div>' } // 2. Define some routes // Each route should map to a component. The "component" can // either be an actual component constructor created via // `Vue.extend()`, or just a component options object. // We'll talk about nested routes later. const routes = [ { path: '/onefoo', component: myFoo }, { path: '/twobar', component: myBar } ] // 3. Create the router instance and pass the `routes` option // You can pass in additional options here, but let's // keep it simple for now. const router = new VueRouter({ routes // short for `routes: routes` }) // 4. Create and mount the root instance. // Make sure to inject the router with the router option to make the // whole app router-aware. const app = new Vue({ router }).$mount('#app') // Now the app has started! </script> </body> </html>
說明:
1、path 為路由路徑,component 為元件檔案(.vue)或內容。
2、router-view 是用來定位路由組件渲染的出口
3、router 可設定的屬性如下
interface RouteConfig = { path: string, component?: Component, name?: string, // for named routes components?: { [name: string]: Component }, // for named views redirect?: string | Location | Function, props?: boolean | Object | Function, alias?: string | Array<string>, children?: Array<RouteConfig>, // for nested routes beforeEnter?: (to: Route, from: Route, next: Function) => void, meta?: any, // 2.6.0+ caseSensitive?: boolean, // use case sensitive match? (default: false) pathToRegexpOptions?: Object // path-to-regexp options for compiling regex }
參考資料: