vue router是vue.js官方的路由管理器。他和vue.js的核心深度集成,让构建单页面应用。
一、安装
// --save的作用是自动把模块和版本号添加到dependencies部分npm install vue-router --save// 如果使用的是vue2版本 需要指定vue-router的版本为3.*.* (3的版本)npm install vue-router@3.5.2 --save// 卸载npm uninstall vue-router
二、配置使用
1、router-link的方式
在
**main.js**中引入并使用**vue-router**模块import Vue from 'vue'// 1.引入vuerouter组件import VueRouter from "vue-router"// 2.使用路由组件Vue.use(VueRouter)
创建切换页面的视图 ```vue
我是HELLO页面
我是HOME页面
4. **对router进行配置**```javascript// 1.定义路由const routes = [{ path: "/home", component: Home },{ path: "/hello", component: Hello },];// 2.创建router实例,然后传“routes”配置const router = new VueRouter({routes: routes})new Vue({render: h => h(App),router // 挂载实例}).$mount('#app')
2、编程式导航方式
<template><div><h3>我是HELLO页面</h3><button @click="clickHandle">点我跳转home</button></div></template><script>export default {methods: {clickHandle() {// 两种方式// 编程式导航 字符串方式this.$router.push("/home");// 编程式导航 对象方式/*this.$router.push({path: "/hello",});*/},},};</script><style></style>
3、Vue CLI
创建项目时,直接添加路由配置
