@路由的基本使用:
1.通过Vue.use(插件)安装插件
2.配置路由和组件之间的映射关系
3.导出对象传入到vue实例中
4.挂载
创建Home,About,User三个组件
Home.vue
<template>
<div>
<h2>我是首页</h2>
<p>哈哈哈</p>
</div>
</template>
<script>
export default {
name: "Home"
}
</script>
<style scoped>
</style>
About.vue
<template>
<div>
<h2>我是关于</h2>
<p>呵呵呵</p>
</div>
</template>
<script>
export default {
name: "About"
}
</script>
<style scoped>
</style>
User.vue
<template>
<div>
<h2>我是我的</h2>
<p>嘻嘻嘻</p>
{{UserId}}
</div>
</template>
<script>
export default {
name: "User",
computed:{
UserId(){
return this.$route.params.userid
}
}
}
</script>
<style scoped>
</style>
index.js
import Vue from 'vue'
import Router from 'vue-router'
//方法一
// import Home from "../components/Home";
// import About from "../components/About";
// import User from "../components/User";
//方法二:router懒加载
const Home = () => import("../components/Home")
const About = () => import("../components/About")
const User = () => import("../components/User")
//1通过Vue.use(插件)安装插件
Vue.use(Router)
//2配置路由和组件之间的映射关系,注意关键字routes,不要写成router或routers
const routes = [
//redirect重定向,首次加载浏览器时就显示Home
{
path: '',
redirect:'/home'
},
{
path: '/home',
component: Home
},
{
path: '/about',
component: About
},
{
path: '/user/:userid',
component: User
}
]
//3导出对象传入到vue实例中
export default new Router({
routes,
mode:'history', //hash模式转为html5的history模式(去#号)
linkActiveClass:'active'
})
App.vue
<template>
<div id="app">
<!-- replace:不会留下history记录,返回键不能按-->
<router-link to="/home" tag="button" replace>首页</router-link>
<router-link to="/about" tag="button" replace>关于</router-link>
<!-- 动态绑定路由-->
<router-link :to="'/user/'+userId" tag="button" replace>我的</router-link>
<!-- router-view决定渲染位置-->
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App',
//组件里的数据data必须是函数
data(){
return{
userId:'zhangsan'
}
}
}
</script>
<style>
</style>
main.js
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
data:{
message:'123'
},
router, //挂载
//箭头函数
// (h) => {
// return h(App)
// }
render: h => h(App) //省略写法
})
路由懒加载后会出现以下文件:
运行结果:
点击我的: