在 Vue.js 中向路由链接传递数据
由 Mux 赞助的 DEV 全球展示挑战赛:展示你的项目!
大家好。在这篇文章中,我将展示如何在 Vue.js 中向 router-link 传递数据。假设我们有一个使用 vue-cli 创建的 Vue 项目。我们有一个名为HelloWorld的组件。默认情况下,Vue 项目中会有一个名为 HelloWorld 的组件。我们将创建一个名为Profile 的新组件。
例如,您不应该使用如下的查询字符串:
https://localhost/#/profile/2
你可以直接将参数作为 props 使用,无需使用查询字符串。让我们开始吧。
创建 Profile.vue 组件
我将创建一个名为Profile.vue的 Vue 组件。它看起来会是这样:
<template>
<div>
{{ welcome }}
</div>
</template>
<script>
export default {
name: 'Profile',
props: ['msg'],
data() {
return {
welcome: 'This is your profile'
}
},
mounted() {
if (this.msg) {
this.welcome = this.msg
}
}
}
</script>
以上代码包含一个名为msg的属性,并返回一个名为welcome 的对象。当有人直接打开此页面时,应该看到“这是您的个人资料消息”。如果有人从其他路由访问此页面,又会怎样呢?
HelloWorld.vue 的修改
让我们设想一下,如果有人通过 router-link 从其他路由访问我们这里,我们的组件应该像这样:
<template>
<div class="hello">
<router-link :to="{ name: 'Profile', params: { msg } }">
Go to your profile
</router-link>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
msg: `This is Ali's profile`
}
}
}
</script>
在上面的代码中,我们有一个 msg 对象,需要将其传递给另一个路由。当用户点击“前往个人资料”链接时,页面会重定向到http://localhost:8080/#/profile页面。但是,我们在 Vue DevTools 中看不到任何数据,因为我们没有配置路由文件。
路由器文件配置
路由器文件应该如下所示:
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Profile from '@/components/Profile'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/profile',
name: 'Profile',
component: Profile,
props: true
}
]
})
我们看到 profile 路由有 props 键,其值为 true。让我们在 Vue DevTools 中检查一下。
如果路由配置是这样的呢?
{
path: '/profile',
name: 'Profile',
component: Profile,
props: false
}
它不会传递数据。
感谢阅读。希望这篇文章对您有所帮助。您可以访问 Vue Router官网了解更多详情。
文章来源:https://dev.to/itachiuchiha/passing-data-to-a-router-link-in-vuejs-2cb0


