vue-router参数传递
vue-router参数传递
通过 :to 和 query 进行参数传递
URL 是表示资源位置的字符串。
解析URL (维基百科) <scheme>
方案+<host>
主机+<port>
端口+<hostport>
主机及端口+<path>
路径+<query>
请求+<fragment>
片段+<host-specific>
主机待定
其中,query为请求
参考代码:
在入口vue文件App.vue中配置对应Profile文件
<!-- vue2 App.vue -->
<template>
<!-- 注意:此处to加了:即v-bind:之后属性值才会是对象,否则就是普通的字符串 -->
<router-link :to="{path:'/profile',query:{name:'zzwi',gender:'man'}}">Profile</router-link>
</template>
<!-- vue2 Profile.vue -->
<template>
<div>
<h2>我是Profile标题</h2>
<p>我是Profile内容</p>
<p>{{$route.query.name}}</p>
<p>{{$route.query.gendle}}</p>
</div>
</template>
运行效果
我是Profile标题
我是Profile内容
zzwi
man
通过 methods 和 query 进行参数传递
在入口vue文件App.vue中设置methods
// vue2
// App.vue
<template>
<div>
<button @click="profileClick">Profile</button>
</div>
</template>
<script>
export default {
name: 'App',
methods: {
profileClick() {
this.$router.push({
path: '/profile',
query: {
name: 'zzwi',
gendle: 'man'
}
})
}
}
}
</script>
通过 params 进行参数传递
通过配置路由格式
{
// 配置动态路由
path:'/user/:id'
}
在入口文件App.vue的路径传递方式:在path后面跟上对应的值
<template>
<div>
<router-link to="/user/123"></router-link>
</div>
</template>
之后便能生成路径:/user/123
this.$router.push() 和 params
在router文件夹的入口文件中配置路由
// vue2
// router/index.js
const routes = [
{
path: '/user'
name: 'User',
// 懒加载
component: () => import("../views/User.vue")
}
]
通过name获取页面,传递params
this.$router.push({name: 'User',params:{a:aaa,b:bbb,c:ccc}})
之后就可以在目标页面进行对数据的各种操作
下面是自己写的一个小例子:
思路是这样的,在Home页面设置一个按钮,点击之后能跳转到User页面并展示一些User页面一开始没有的东西
在路由文件中配置相关路由,
// vue2
// /router/index.js
const routes = [
{
path: '/',
name: 'Home',
component: () => import('../views/Home.vue')
},
{...},
{...},
{
path: '/user',
name: 'User',
component: () => import('../views/User.vue')
}
]
在Home.vue中配置按钮和点击事件
<!-- vue2 Home.vue -->
<template>
<div>
<button @click="userClick">User按钮</button>
</div>
</template>
<script>
export default {
name: 'Home',
methods: {
userClick(){
this.$router.push({name:'User',params:{a:'aaa',b:'bbb',c:'ccc'}})
}
}
}
</script>
在User.vue中进行对传入参数的处理
<!-- vue2 User.vue -->
<template>
<h2>我是User标题</h2>
<p>我是User内容</p>
<div>
<p>{{this.$route.params.a}}</p>
<p>{{this.$route.params.b}}</p>
<p>{{this.$route.params.c}}</p>
</div>
</template>
<script>
export default {
name: 'User'
}
</script>
运行结果如下: