首页 > 解决方案 > vuejs router.go(-1)第二次没有显示

问题描述

我目前正在使用 vue-router 来管理我项目的不同 Vue。

我的 main.js

import Vue from 'vue'
import App from './App.vue'
import jQuery from 'jquery'
import 'bootstrap'

import 'bootstrap/dist/css/bootstrap.css'
global.jQuery = jQuery
global.$ = jQuery

import './assets/css/animate.css'

import router from './router'
import store from './vuex'

Vue.config.productionTip = false

new Vue({
  store,
  router,
  render: h => h(App)
}).$mount('#app')

当我第一次在我的仪表板('/dashboard')上时,会调用'created'方法。从 API 中检索数据并显示在我的数组中。

之后,我单击数组中的一个元素,该元素将我路由到“/details/:id”(其中 id 是我的元素的 id)。一切正常,然后我单击“返回”按钮。

我在仪表板页面上再次完成,我看到再次调用了“创建”方法,数据已从 API 中很好地检索,但没有显示任何内容,并且我的数组保持为空。

我真的不明白为什么。

有'created'函数的代码:

export default {
  created: function() {
    console.log('created => dashboard');
    let store = this.$store;
    let q = this.rows; 

    //get rows 
    if (store.state.socket.io._callbacks["$rows"] == undefined) {
      console.log("Binding rows");
      //Where I receive the rows from API
      store.state.socket.io.on("rows", data => {
        console.log("rows reponse:", data);
        if (data.success) {
          this.nbrItems = data.rows.length;
          q.splice(0, q.length); //Clean the array without replacing the instance
          data.rows.map(a => q.push(a));
          console.log("Queue length: " + q.length);
        }
      });
    }
    //get the queue
    this.refresh(); // This send a request to the API to ask it to send us back the datas
  },

this.$router.go(-1)用来导航回“/dashboard”页面。

编辑:是否存在状态问题或类似问题?我不明白为什么,因为在内存中我可以访问所有数据,不再有绑定......

标签: vue.jsvue-router

解决方案


我想通了:

问题来自socket.io。我正在检查事件是否在订阅函数之前已经绑定,并且该函数包含仍然引用先前的 Vue 实例的“this”。

通过替换这个简单地修复:

  //get rows 
    if (store.state.socket.io._callbacks["$rows"] == undefined) {
      console.log("Binding rows");
      //Where I receive the rows from API
      store.state.socket.io.on("rows", data => {
        console.log("rows reponse:", data);
        if (data.success) {
          this.nbrItems = data.rows.length;
          q.splice(0, q.length); //Clean the array without replacing the instance
          data.rows.map(a => q.push(a));
          console.log("Queue length: " + q.length);
        }
      });
    }

这样:

    if (store.state.socket.io._callbacks["$rows"] != undefined) {
      store.state.socket.io.off("rows");
    }
    console.log("Binding rows");
    store.state.socket.io.on("rows", data => {
      console.log("rows reponse:", data);
      if (data.success) {
        this.nbrItems = data.rows.length;
        q.splice(0, q.length);
        data.rows.map(a => q.push(a));
        console.log("Queue length: " + q.length);
      }
    });

但这让我想知道,如果我仍然可以访问以前的 Vue 实例,这是否意味着随着时间的推移它会发生某种内存泄漏?

我想垃圾收集器不会,但意味着没有其他内容涉及前一个实例。


推荐阅读