【问题标题】:Vue.js route params data getting lost after the full page reloadVue.js 路由参数数据在整个页面重新加载后丢失
【发布时间】:2020-09-19 15:35:39
【问题描述】:

我正在使用参数从路由器链接传递用户 ID,以在配置文件页面中显示用户的详细信息,并且我正在获取所有必需的数据并且也正确显示,但是一旦我重新加载页面,$ route.params.id 更改为 undefined 并且显示的数据已消失以获取数据,我必须再次导航到索引页面并重新访问链接。

我的带有路由器链接的 index.vue 页面如下

<h6 class="author">
    <router-link :to="{name: 'FrontProfile' , params: {
         id: post.user.id }}"
         tag="a" active-class="active">{{post.user.name}}
    </router-link>
</h6>

我的个人资料页面代码是:

data(){
       return {
               id: this.$route.params.id,
               user: {},
               thoughts: {},
               }
        },
methods:{
         viewProfile() {
            axios.get('user_profile/' + this.id).then((response) => {
                this.user = response.data.user_data;
                this.thoughts = response.data.thoughts;
            }).catch(() => {

            });
        },
 watch:{
        '$route' : 'viewProfile'
    },
created() {
        this.viewProfile();
    }           

我可以尝试什么来解决这个问题?

【问题讨论】:

  • 你能在 CodePen 中重现这个问题吗?其他疑问,重新加载页面后,id 在 URL 中?
  • 也发布您的路线文件。
  • 其他想法:可能created事件有问题,尝试使用mounted事件。
  • 如果在您刷新配置文件 url 上的浏览​​器时发生这种情况,那么听起来这可能与您如何捕获 url 服务器端有关,也许 id 没有通过那里传递。
  • @GabrielWillemann 我也会按照你的要求在 codepen 中发布问题。

标签: vue.js vuejs2 vue-component vue-router


【解决方案1】:

您是否考虑过将您的 id 作为计算属性? 如果你把它留在组件数据中,它只会在创建组件时更新,你可以通过 $route 移除观察者,这是比计算属性更高的操作。

data(){
  return {
    user: {},
    thoughts: {},
  }
},
methods:{
 viewProfile() {
    // You can use destructuring here over your response
    axios.get('user_profile/' + this.id).then(({ data: { user_data, thoughts } }) => {
        this.user = user_data;
        this.thoughts = thoughts;
    }).catch(() => {

    });
},
computed: {
  id() {
    return this.$route.params.id;
  }
},
// because of the vue lifecycle hooks, this should be a `mounted` hook intead of a `created`
mounted() {
  this.viewProfile();
} 

【讨论】:

  • 我也试过了,但是问题还没有解决,伙计。刷新后仍然无法获取id。
【解决方案2】:

抱歉,我通过更改一些路线配置解决了问题。非常感谢您的努力。我的 web 路由和 vue 路由发生冲突,已解决。

【讨论】:

    猜你喜欢
    • 2021-01-17
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    相关资源
    最近更新 更多