简体   繁体   English

Vue路由器参数未在页面中更新

[英]Vue Router params not updating in page

Hello I have some conditional logic in my view based on the current page您好,根据当前页面,我的视图中有一些条件逻辑

in setup I have在设置中我有

const curVidType = ref(route.params.videoTopic);

I return it and then print out like我退回它然后打印出来

<h1>Welcome to  {{ curVidType }} videos</h1>

However it only works if I refresh.但是,它仅在我刷新时才有效。 If I browse to a new page it stays the old one even though the browser url changes.如果我浏览到新页面,即使浏览器 url 发生变化,它仍然是旧页面。 after refresh it updates.刷新后更新。 Thanks so much for any help非常感谢您的帮助

You're initializing the variable as a const, which means it does it once and then doesn't set it.您将变量初始化为 const,这意味着它执行一次然后不设置它。 If you change curVidType to a computed value, you can have it react to changes in the router params.如果将 curVidType 更改为计算值,则可以让它对路由器参数中的更改做出反应。

computed: {
  curVidType() {
    return route.params.videoTopics
  }
}

This will have the value of curVidType set to change when videoTopics does这将设置 curVidType 的值,以在 videoTopics 执行时更改

EDIT:编辑:

Having read the comments and looked at the comments and read some of the documentations, ref() will create a reactive object but I'm not sure it's reacting to the original object.阅读评论并查看评论并阅读一些文档后, ref() 将创建一个反应式 object 但我不确定它是否对原始 object 做出反应。 But it looks like the toRef() function can create that bridge.但看起来toRef() function 可以创建那个桥。

const curVidType = toRef(route.params, 'videoTopics')

Should allow for curVidType.value to also reflect changes to to route.params.videoTopics应该允许 curVidType.value 也反映对 route.params.videoTopics 的更改

Would be nice if you could share some more code with us in order to help you.如果您可以与我们分享更多代码以帮助您,那就太好了。 This should just work fine这应该可以正常工作

<template>
{{ curVidType }}
</template>

<script>
import { useRoute } from 'vue-router';

export default {
    setup() {
        const { params } = useRoute();
        const curVidType = params.videoTopic

        return {
            curVidType,
        };
    },
};
</script>

Try adding :key to your Component to make sure it updates when param changes:尝试将:key添加到您的组件中,以确保它在参数更改时更新:

<your-component :key="$route.params.videoTopic"></your-component>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM