- 使用步驟
- 將vue-router 引入vue下面
- 新建兩個元件login元件和register元件
- 新建router物件,註冊到vm示例上去
- 路由渲染的兩個方式
- a標籤
<a href="#/lgoin"></a>
- vue-router提供的
<router-link to='login'></router-link>
(推薦)
- 路由啟用類 linkActiveClass
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<style>
/* 路由啟用類 */
.myActive{
color:red;
background-color: brown
}
</style>
</head>
<body>
<div id="app">
<!-- <a href="#/login">登入</a>
<a href="#/register">註冊</a> -->
<router-link to="/login">登入</router-link>
<router-link to="/register">註冊</router-link>
<!-- router佔位符,路由規則匹配的元件,展示到這裡 -->
<router-view></router-view>
</div>
<script>
var login = {
template: '<h1>我是login</h1>'
}
var register = {
template: '<h1>我是register</h1>'
}
// const Foo = { template: '<div>foo</div>' }
// const Bar = { template: '<div>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: '/foo', component: Foo },
// { path: '/bar', component: Bar }
// ]
//每個路由規則,都是一個物件,都有兩個屬性
//屬性1:路徑 連結地址
//屬性2:元件 匹配到path後,展示對應元件
const router = new VueRouter({
routes:[
{path:'/',redirect:'/login'},
{path:'/login',component:login},
{path:'/register',component:register}
],
linkActiveClass:'myActive'
})
// const router = new VueRouter({
// routes // short for `routes: routes`
// })
var vm = new Vue({
el: '#app',
data: {},
methods: {},
//將路由規則物件,註冊到vm示例上,用來監聽vm地址的變化,然後展示對應的物件
router
});
Vue.config.devtools = true
</script>
</body>
</html>
本作品採用《CC 協議》,轉載必須註明作者和本文連結