Vue,有没有办法在没有 URL 参数的路由之间传递数据? [英] Vue, is there a way to pass data between routes without URL params?
问题描述
我正在研究如何在我的 Vue2 应用程序中不使用 URL 参数的情况下在两个单独的组件(不是父组件和子组件)之间秘密传递数据.这并不意味着我在传递机密,而是我只是不希望用户看到它(仅出于 UI 考虑).
I am looking how to pass data secretly between two separate components (not parent and child) without using URL params in my Vue2 app. This doesn't mean I am passing secrets but rather I just dont want the user to see it (only for UI considerations).
我知道 Vue 有 Props 但它们用于在父级之间传递数据和子组件.就我而言,我的 URL 会改变,但我不想通过可见参数传递数据.
I know Vue has Props but they are meant for passing data between parent and child component. In my case, my URL will change but I don't want to pass data via visible params.
有人声称使用没有 URL 参数的 props 在这里,但我一直无法重现一个有效的解决方案(每次都未定义).
Someone claimed to use props without URL params here but I haven't been able to reproduce a working solution (getting undefined each time).
我还查看了这些 选项,但它们都使用我们知道可见的 URL 或查询参数.
I also checked out these options but they are all using either URL or query params which as we know are visible.
一个丑陋的解决方案是将数据写入本地存储,然后在那里读取,但这会产生大量开销和复杂性(例如,如果我只希望这些数据被读取一次,等等).
An ugly solution would be to write the data to local storage and then read it there but this creates a lot of overhead and complexity (like what if I only want this data to be read once, etc).
这个问题有没有更优雅的解决方案?
Is there a more elegant solution to this problem?
谢谢!
推荐答案
- make props: true for the destination route -- 在路由器的 index.js 文件中
{
path: '/home',
name: 'home',
component: taskChooser,
props: true,
}
在组件中定义 props,例如 props: ['myprop'], - 注意引号
define prop in the component e.g props: ['myprop'], - note the quotes
将要从源路由传递的变量复制到与 prop 相同的名称中 - 在本例中为 myprop
copy the variable you want to pass from the source route into the same name as your prop - in this case myprop
myprop = theVariableThatYouWantToPass
this.$router.replace({name:'home', params:{myprop}});
确保道具和变量的名称相同 - 道具在引号中.
它对我有用.
这篇关于Vue,有没有办法在没有 URL 参数的路由之间传递数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!