vue-router学习
创建vue-cli项目
- 勾选router选项
- vue-router适合构建单页面应用
- https://router.vuejs.org/zh/
配置路由
- src/router/index.js(vue-cli4创建项目时勾选会自动生成)
//导入相应文件与包 import Vue from 'vue' import VueRouter from 'vue-router' import Home from '../views/Home.vue' //通过Vue.use(插件),安装插件 Vue.use(VueRouter) //创建VueRouter对象 const routes = [ { path: '/', name: 'Home', component: Home } ] //配置路由和组件之间的应用关系 const router = new VueRouter({ routes }) //将router导出传入Vue实例 export default router
- 组件的绑定方法:
import Home from '../views/Home.vue' const routes = [ { path: '/', name: 'Home', component: Home } ]
const routes = [ { path: '/about', name: 'About', component: () => import('../views/About.vue') } ]
- 组件的绑定方法:
- main.js
import router from './router' new Vue({ router, render: h => h(App) }).$mount('#app')
- App.vue
<template> <div id="app"> <div id="nav"> <router-link to="/">Home</router-link> | <router-link to="/about">About</router-link> </div> <router-view/> </div> </template>
- router-link 标签是路由,会被渲染成 a 标签
- router-view 标签会根据当前的路径,动态渲染出不同的组件
重定向路由
- src/router/index.js(添加redirect属性来重定向路由)
const routes = [ { path: '/', name: 'Home', component: Home redirect : '/home' } ]
设置history模式
- vue-router 默认 hash 模式 —— 使用 URL 的 hash 来模拟一个完整的 URL,于是当 URL 改变时,页面不会重新加载。如果不想要很丑的 hash,我们可以用路由的 history 模式,这种模式充分利用 history.pushState API 来完成 URL 跳转而无须重新加载页面
- src/router/index.js(添加mode属性设置)
const router = new VueRouter({ routes, mode:'history' })
router-link补充
- tag属性:tag可以指定router-link之后渲染成什么组件
<router-link to="/" tag="button">Home</router-link>
- replace属性:replace不会留下history记录,所以指定replace的情况下,后退键不能返回上一个页面中
<router-link to="/" tag="button" replace>Home</router-link>
- active-class属性:DOM激活时的样式设置
- 单个标签修改
<router-link to="/" tag="button" replace active-class="active">Home</router-link> <style> .active{ color:red; } </style>
- 总体修改(src/router/index.js)
const router = new VueRouter({ routes, mode:'history', linkActiveClass:'active' })
通过代码跳转路由
- 绑定点击事件
<button @click="homeClick">home</button> <button @click="aboutClick">about</button>
- 点击事件
<script> //replace函数与push函数皆可达到跳转效果 export default{ name:'App', methods:{ homeClick(){ console.log('homeClick'); this.$router.replace('/'); // this.$router.push('/'); }, aboutClick() { // this.$router.push('/about'); this.$router.replace('/about'); console.log('aboutClick') } } } </script>
- this.$router.push():跳转到不同的url,但这个方法会向history栈添加一个记录,点击后退会返回到上一个页面
- this.$router.replace():同样是跳转到指定的url,但是这个方法不会向history里面添加新的记录,点击返回,会跳转到上上一个页面。上一个记录是不存在的
动态路由的使用
- src/router/index.js(在url后面加 :属性名 来实现动态路由)
const routes = [ { path: '/user/:userId', name: 'User', component: User, } ]
- App.vue(使用v-bind绑定传送数据)
<router-link v-bind:to="'/user/'+userId">User</router-link> <script> export default{ name:'App', data(){ return { userId:'goodhu' } } } </script>
不同页面间传值
- User.vue(此时的userId对应index.js中设置的属性名)
<p>{{userId}}</p> <script> export default { name: 'User', computed: { userId(){ return this.$route.params.userId; } } } </script>