我是 vue 的新手。
比方说,这是我的 URL:https://mywebsite.com/states/ABC?query=
和 https://mywebsite.com/search?query=
我正在使用 $route.path
获取路径 /states/ABC
和 /search
。我正在 mounted()
现在,基于 $route.path
的这个值,我想触发不同的方法,例如,如果它是 states
,那么 statesEvent()
如果是 search
,则 searchEvent
。
EDITED:这两个事件都存在于 mixin 中。我正在将该 mixin 加载到该组件中。
最佳答案
this.$route.path
是一个简单的字符串,您可以使用任何 Javascripts 字符串匹配运算符(从 ==
到 match(/regex/)
到 includes
等)。
在您的特定情况下,我建议您使用
const path = this.$route.path
if(path.startsWith('/states') {
// execute states specific code
}
else if(path.startsWith('/search')) {
// search specific code
}
关于javascript - 如何根据$route.path 的值调用各种函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58624737/