vue路由跳转(切换网页)
引入
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
1、创建路由实例
// 创建index路由实例 let index = { template: '#index' } // 创建mine路由实例 let mine = { template: '#mine', } // 1、创建路由实例 const router = new VueRouter({ })
2、创建映射关系
const router = new VueRouter({ // 2、创建映射关系 routes: [ { path: '/', // 路由重定向,即展示页面为/时自动切换到index redirect: '/index' }, { path: '/index', component: index }, { path: '/mine', component: mine } ], })
3、建立联系,将路由挂在在vue实例上
const vm = new Vue({ el: '#app', data: { }, // 3、建立联系,将路由挂载在vue实例上 // router:router, // 简写router router, methods: { }, })
4、展示位置/声明两个组件
<div id='app'>
<router-link to='/index' tag='span'>去首页</router-link>
<router-link to='/mine' tag='span'>去个人中心</router-link>
<!-- 4、展示位置 -->
<router-view></router-view>
</div>
<!-- 声明两个组件 -->
<!-- index首页组件 -->
<template id="index">
<div>
<div>首页</div>
</div>
</template>
<!-- mine个人中心组件 -->
<template id="mine">
<div>
<div>个人中心</div>
</div>
</template>
完整代码展示:
<!DOCTYPE html>
<html>
<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></title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<style>
.router-link-active {
color: red;
font-size: 30px;
}</style>
</head>
<body>
<div id='app'>
<router-link to='/index' tag='span'>去首页</router-link>
<router-link to='/mine' tag='span'>去个人中心</router-link>
<!-- 4、展示位置 -->
<router-view></router-view>
</div>
<!-- 声明两个组件 -->
<!-- index首页组件 -->
<template id="index">
<div>
<div>首页</div>
</div>
</template>
<!-- mine个人中心组件 -->
<template id="mine">
<div>
<div>个人中心</div>
</div>
</template>
<script>
// 创建路由实例
// 创建index路由实例
let index = {
template: '#index'
}
// 创建mine路由实例
let mine = {
template: '#mine',
}
// 1、创建路由实例
const router = new VueRouter({
// 2、创建映射关系
routes: [
{
path: '/',
// 路由重定向,即展示页面为/时自动切换到index
redirect: '/index'
},
{
path: '/index',
component: index
},
{
path: '/mine',
component: mine
}
],
//增加选中效果,如果添加下面这句在style中应该使用.active改变样式
//linkActiveClass: 'active'
})
const vm = new Vue({
el: '#app',
data: {
},
// 3、建立联系,将路由挂载在vue实例上
// router:router,
// 简写
router,
methods: {
},
})
</script>
</body>
</html>
展示结果:



浙公网安备 33010602011771号