Vue—router实现路由跳转
目录
- Vue---router实现路由跳转
- 基本使用
- 路由跳转
- html实现路由跳转
- JS实现路由跳转
基本使用
所谓路由,就是将一个个组件映射到不同的路由url中
首先要将App内的内容换成router-view
// App.vue
<template><div id="app"><router-view></router-view></div>
</template>
<script>
export default {data() {return {}},components:{}
}
</script>
- 这个意思是
router-view
这部分以后都会以路由组件生效
现在去注册路由,还是以上面的Active组件为例
打开src/router/index.js
文件
import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import Active from '@/components/Active.vue'Vue.use(VueRouter)const routes = [{path: '/',name: 'home',component: HomeView},{path: '/about',name: 'about',// route level code-splitting// this generates a separate chunk (about.[hash].js) for this route// which is lazy-loaded when the route is visited.component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')},{path: '/active',name: 'active',component: Active},
]const router = new VueRouter({mode: 'history',base: process.env.BASE_URL,routes
})export default router
import Active from '@/components/Active.vue'
导入Activepath: '/active'
:浏览器通过访问这个路径来显示这个组件name: 'active'
:组件名component: Active
:传入组件
import Active from '@/components/Active.vue'
导入Active
path: '/active'
:浏览器通过访问这个路径来显示这个组件name: 'active'
:组件名component: Active
:传入组件
现在访问active路径就可以显示Active组件了
路由跳转
核心代码为<router-link to=""></router-link>
而跳转的路径要以router/index.js中的path为准
html实现路由跳转
<router-link to="/home"><button>点我跳转至home</button>
</router-link>
JS实现路由跳转
toHome(){this.$router.push('/home')
}