vue-router思想:相当于后端的路径对应得controller,
前端的路由就是路径对应要展示组件
路由就是一种对应关系!!!
官网:https://router.vuejs.org/zh/guide/
编程式导航(路由)
安装vue-router:
https://router.vuejs.org/zh/installation.html#%E7%9B%B4%E6%8E%A5%E4%B8%8B%E8%BD%BD-cdn
如果是vue3,则安装vue-router4,vue2,就安装router3
npm install vue-router@3
vue配置常规插件套路
1、下载后再main.js中引入后配置!
引入插件
import VueRouter from ‘vue-router’
// 应用插件
Vue.use(VueRouter)
创建一个路由器,用于给vue引入配置
创建router文件夹,中创建路由js:index.js
// 该文件用于专门创建路由器
import VueRouter from 'vue-router'
import About from '../components/About'
import Home from '../components/Home'
// 创建并暴露一个路由器
export default new VueRouter({
routes:[
{
path:'/about',
component:About
},
{
path:'/home',
component:Home
}
]
})
// 引入路由器–index.js可以不用写
import router from ‘./router’
配置路由 router:router
在vue引入并使用路由后,就有router的配置项可以在new的时候配置了,然后将自己创建的路由器引入后配置进去
new Vue({
render: h => h(App),
router:router,
beforeCreate(){
Vue.prototype.KaTeX parse error: Expected 'EOF', got '}' at position 25: …s //安装全局事件总线 }̲ }).mount(‘#app’)
代码实现简单路由
创建一个专门的放组件的包pages:
创建Home和About组件
about:
<template>
<div class="About">
<h1>About</h1>
</div>
</template>
<script>
export default {
name:'About',
data(){
return{
}
},
methods:{
}
}
</script>
<style scoped>
.About{
background-color: bisque;
}
</style>
home:
<template>
<div class="Home">
<h1>Home</h1>
</div>
</template>
<script>
export default {
name:'Home',
data(){
return{
}
},
methods:{
}
}
</script>
<style scoped>
.Home{
background-color: aqua;
}
</style>
在app中应用
<template>
<div class="app">
<h1>{{msg}}</h1>
<School :getSchoolName="getSchoolName"/>
<!-- <Student v-on:atguigu="getStudentName"/> -->
<Student ref="student"/>
<!-- vue中借助ruoter-link 标签实现路由的切换 -->
<router-link active-class="active" to='/about'>About</router-link>
<br/>
<router-link active-class="active" to='/home'>Home</router-link>
<div class="router_view">
<router-view></router-view>
</div>
</div>
</template>
<script>
import School from './components/School'
import Student from './components/Student'
export default {
name: 'App',
components: {
School,
Student
},
data(){
return{
msg:'你好!'
}
},
methods:{
getSchoolName(name){
console.log('app收到了schoole的数据:',name)
},
getStudentName(name){
console.log('app收到了student的数据:',name)
},
demo(){
console.log('demo绑定')
}
},
mounted(){
this.$refs.student.$on('atguigu',this.getStudentName)
this.$refs.student.$on('demo',this.demo)
}
}
</script>
<style>
.app{
background-color: bisque;
}
.router_view{
background-color: aliceblue;
}
</style>
结果: