如何在Vue.js中获取HTTP引用?

3

我希望能够获取用户从哪个页面进入我的页面。

目前,我希望在我的created()或mounted()页面中获取此信息。使用this.$router或this.$route,但它们都不包含此信息。

我知道在导航守卫中,我们可以使用以下代码:

router.beforeEach((to, from, next) => { })

想知道页面来自哪里,但我不想使用router.beforeEach,因为它在我的main.js中,而我想获取referer的位置在我的组件页面中,可以在created/mounted方法中实现吗?

这个可能吗?


你可以将路由器作为属性传递下去,或者使用这里详细介绍的某种事件系统:https://vuejs.org/v2/guide/migration.html#dispatch-and-broadcast-replaced - Brian Glaz
你是什么意思说"将路由器作为属性传递下来"?我在文档中找不到这个。 - hidar
@hidar 这就是你要找的文档。https://router.vuejs.org/zh/essentials/passing-props.html - Onur Özkan
3个回答

2

您可以在App.vue的mounted()钩子中使用this.$route.query。您不需要使用router.beforeEach,因为这没有意义。App.vue仅在应用程序加载时挂载一次,因此这是检查路由器查询参数的好地方。


我现在正在尝试这个,它完美地运行了。我的代码在mounted中:console.log(this.$route.query); 和url是 product/3?utm_source=2。控制台记录了 {utm_source: "2"} - Vladislav Gritsenko
嗯..很抱歉回复晚了,我又遇到了这个问题,但还是无法找到来源。我有以下代码:mounted () { console.log('this.$route.query', this.$route.query) } - hidar
我不知道还能做什么来获取引用者。我需要传递一个属性或其他东西吗? - hidar

0

router.beforeEach((to, from, next) => { })

寻找to.fullPath。这是你的重定向链接。

-1
router.beforeEach((to, from, next) => {
       console.log(to.query)
       console.log(to.query.utm_source)
})

如果网址是 product/3?utm_source=2. 控制台输出

{utm_source: "2"}
2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接