第一步router文件夹里新建index.js
// router文件夹里面的index.js
// 1. 引入vue和vue-router
import Vue from 'vue'
import VueRouter from 'vue-router'
// 引入需要的组件
import Home from '../components/Home.vue'
import About from '../components/About.vue'
// 2. 在vue中使用路由
Vue.use(VueRouter)
// 从路由对象中抽出来写,看起来简介,里面一个{}对应一个URL
// path:是路径的意思,这里跟url地址一样
// component:是注册组件,进入那个path就直接注册这个组件
// redirect:重定向的意思,刚打开页面的时候就让他重定向到那个界面
const abcd = [
{
path: '',
redirect: '/home'
},
{
path: '/home',
component: Home
},
{
path: '/about',
component: About
}
]
// 3. 创建路由对象
const router = new VueRouter({
// routers是固定写法
routes: abcd,
// 默认是HASH模式,这里可以用mode改成history模式
mode: 'history'
})
// 4. 导出路由
export default router
第二步,导出路由之后在main.js文件中引入并且使用
import Vue from 'vue'
import App from './App.vue'
// 引入刚刚导出的router文件
import router from './router'
Vue.config.productionTip = false
new Vue({
// 在vue里使用它
router,
render: h => h(App),
}).$mount('#app')
第三步,在components文件夹里面新建两个Vue组件
// Home.vue
<template>
<div>
<p>我是Home组件</p>
</div>
</template>
<script>
export default {
name: 'Home'
}
</script>
<style scoped>
</style>
// About.vue
<template>
<div>
<p>我是About组件</p>
</div>
</template>
<script>
export default {
name: 'About'
}
</script>
<style scoped>
</style>
第四步,在App.vue组件里就可以开始使用了
router-link标签里面有: to 、replace、 append、 tag、 active-class、 exact 、 event、 exact-active-class这些属性;这里不再一一解释,可以去官网查看
// 方法1
<template>
<div id="app">
// 路由跳转,到页面上就是个a标签,里面的to属性就是跳转到那个url的
<router-link to="/home">首页</router-link>
<router-link to="/about">关于</router-link>
// 渲染路由跳转的页面
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
<style>
</style>
// 方法2
<template>
<div id="app">
<button @click="homeBtn">首页</button>
<button @click="aboutBtn">关于</button>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App',
methods: {
homeBtn() {
// 在 Vue 实例内部,你可以通过 $router 访问路由实例
this.$router.push('/home')
},
aboutBtn() {
this.$router.push('/about')
}
}
}
</script>
<style>
</style>