简介:Vue Router是Vue.js的官方路由器。它与Vue.js核心深度集成,使用Vue.js构建单页应用程序变得轻而易举。
一、案列图示
二、案例代码:
<!--index.html -->
<!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>
<link rel="stylesheet" href="https://unpkg.com/semantic-ui/dist/semantic.css">
<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">
<div class="ui container">
<div class="ui two item menu">
<router-link class="item" active-class='active' exact to='/'>首页</router-link>
<!-- active-class='active' exact 选中时的css效果 -->
<router-link
class='item'
active-class='active' exact
:to="{name:'events'}">活动</router-link>
<!--:to 动态绑定router-->
</div>
<div class="ui piled segment">
<router-view></router-view>
</div>
</div>
</div>
<script type="text/javascript" src="index.js">
</script>
</body>
</html>
// index.js
const Home ={
template:`<h2>首页</h2>`
}
// {{$route.params.id}}-{{$route.query}}输入路由携带的id、参数
const Event = {
// props:['id'], //以属性的方式接受路由传递的id
template:`<div>
<h2>活动{{'id'}}-{{$route.params.id}}-{{$route.query}}</h2>
<router-view></router-view>
</div>
`,
beforeRouteUpdate (to, from, next) {
console.log('to')
console.log(to) //控制台查看
console.log('from')
console.log(from)
console.log('next:'+next)
next()
}
}
const Comment = {
template:`
<div>
<hr class="ui section divider">
<h2>评论</h2>
</div>
`
}
const routes = [
{
path:'/',
component:Home,
name:'home' //命名
},
{
path:'/abc',
redirect:{name:'home'} //地址http://localhost:3000/#/abc,将会重定向 至home组件
},
{
path:'/events',
component:Event,
name:'events',
alias:'/event' //别名 等效于 path:'/events'
},{
path:'/events/:id',
component:Event,
// props:true,//以属性的方式将id传给组件
children:[
{
path:'comment',
component:Comment
}
]
}
]
const router = new VueRouter({
routes
})
const app = new Vue({
el:'#app',
router
})