vue-router
安装
方式一:通过vue-cli,在项目创建的时候将router勾选上。
方式二:通过命令行安装,然后自自己配置
npm i vue-router -S
配备文件
文件地址:*/src/router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入组件(页面)
import Home from '../views/Home.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Home',
component: Home
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
文件地址 */src/main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router' // 注意这里
import store from './store'
Vue.config.productionTip = false
new Vue({
router, // 注意这里
store,
render: h => h(App)
}).$mount('#app')
路由的跳转
使用router-link
方式一:直接根据路由地址进行跳转
<router-link to="/home">跳转</router-link>
方式二:根据我们配置的路由名字来进行跳转
<router-link :to="{name: 'Home', }">跳转</router-link>
代码方式
this.$router.go(-1)//跳转到上一次浏览的页面
this.$router.replace('/menu')//指定跳转的地址
this.$router.replace({name:'menuLink'})// 指定跳转路由的名字下
this.$router.push('/menu')通过push进行跳转
this.$router.push({name:'menuLink'})通过push进行跳转路由的名字下
其中replace和push的跳转方式不同点在于
push:会保存上一个页面,浏览器可以上一步回退到上一个网页
replace:跟上面相反
核心路由的传递参数
使用router-link进行传参
<router-link :to="{name: 'Home',params: { key: '我是参数' } }">跳转</router-link>
// 所有的参数写到params对象里边,路由会自动检测
// 获取值
调用 this.$route.params
通过配置router的path(就是地址)传递参数-------不常用
const routes = [
{
path: '/home/:name',
name: 'Home',
component: Home
}
]
传递参数方式一: 使用手敲网页地址
http://localhost:8080/home/15 这个15就是name的值
传递方式二
<router-link to="/home/15">跳转</router-link>
// 获取值
调用 this.$route.params
通过代码进行传参
this.$router.push({
name: 'Home',
params: {
qian: 'wd'
}
})
// 获取值
调用 this.$route.params