Vue-Router动态路由
作用:动态拼接一些路径语法:/user/:userId(:XX表示可以动态拼接,路径可以渲染成/user/zhangsan或者/user/lisi等等)1.通过router-link渲染的跳转页面通过动态绑定to属性后面跟着动态路由来跳转页面(:to="’/about/’+info")Router-Index.jsimport Vue from 'vue';import VueRouter fro
·
作用:动态拼接一些路径
语法:/user/:userId(:XX表示可以动态拼接,路径可以渲染成/user/zhangsan或者/user/lisi等等)
1.通过router-link渲染的跳转页面
- 通过动态绑定to属性后面跟着动态路由来跳转页面(:to="’/about/’+info")
Router-Index.js
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
const About = () => import('../views/About.vue');
const routes = [
{
path: '/about/:info',
component: About
}
];
const router = new VueRouter({
routes,
mode: 'history',
linkActiveClass: 'active'
});
export default router;
App.vue
<template>
<div>
<!-- 通过router-link动态路由传参 -->
<router-link :to="'/about/'+info">About</router-link>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
info: 'hello vuejs'
}
}
}
</script>
<style>
.active {
color: #1890ff;
}
</style>
About.vue
<template>
<div>
<h2>About</h2>
<!-- 可以通过($route.params.动态传参)获取数据 -->
<p>{{ $route.params.info }}</p>
</div>
</template>
<script>
export default {
name: 'About'
}
</script>
<style>
</style>
2.通过普通标签渲染的跳转页面
- 通过this.$router.push(’/user/’ + this.userId)获取数据
Router-Index.js
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
const User = () => import('../views/User.vue');
const routes = [
{
path: '/user/:userId',
component: User
}
];
const router = new VueRouter({
routes,
mode: 'history',
linkActiveClass: 'active'
});
export default router;
App.vue
<template>
<div>
<!-- 通过普通button动态路由传参 -->
<button @click="userClick">用户</button>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
userId: 'zhangsan'
}
},
methods: {
userClick() {
this.$router.push('/user/' + this.userId);
}
}
}
</script>
<style>
.active {
color: #1890ff;
}
</style>
User.vue
<template>
<div>
<h2>User</h2>
<p>{{ $route.params.userId }}</p>
</div>
</template>
<script>
export default {
name: 'User'
}
</script>
<style>
</style>
更多推荐
已为社区贡献4条内容
所有评论(0)