1. $route.params
(1)新建组件
新建一个User.vue文件,添加
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| <template> <div> <h2>user(用户的相关内容)</h2> <p>userId:{{userId}}</p> </div> </template>
<script> export default { name: "User", computed: { userId() { return this.$route.params.userId; } } }; </script>
|
(2)设置映射
打开index.js文件,添加如下代码:
1 2 3 4 5
| { path: "/User/:userId", component: User, name: User, }
|
(3)App.js
打开App.js文件
2. $route.query
(1)新建组件:profile.vue,添加如下代码
1 2 3 4 5 6 7 8 9 10 11 12
| <template> <div> <h2>profile</h2> <p>{{$route.query}}</p> <p>{{$route.query.name}}</p> </div> </template> <script> export default { name: "profile" }; </script>
|
$route.query是一个对象,里面是页面传过来的数据
(2)设置映射
打开index.js文件,添加如下代码
1 2
| const profile = () => import ("../components/Profile.vue");
|
1 2 3 4 5
| { path: "/profile", name: profile, component: profile, }
|
(3)打开App.vue,添加如下代码
1 2 3 4
| <router-link :to="{path: '/profile',query: {name:'WRM',sex: 'girl',height: '166'}}" tag="button" >profile</router-link>
|
3.如果不用<router-link>标签该如何传递参数?
例如,把原来的
1 2 3 4
| <router-link :to="{path: '/profile',query: {name:'WRM',sex: 'girl',height: '166'}}" tag="button" >profile</router-link>
|
替换为button
1
| <button @click="profileClick">profile</button>
|
在methods里添加:
1 2 3 4 5 6 7 8 9 10
| profileClick() { this.$router.push({ path: "/profile", query: { name: "WRM", sex: "girl", height: "166" } }); }
|
其余的和2.一样