Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

对于 #140 这个问题 #1295

Closed
zxzhgk opened this issue Dec 28, 2018 · 3 comments
Closed

对于 #140 这个问题 #1295

zxzhgk opened this issue Dec 28, 2018 · 3 comments

Comments

@zxzhgk
Copy link

zxzhgk commented Dec 28, 2018

[在此简单描述您的建议]

#140 页面跳转后上一个vue实例不会释放,重新跳回那个页面会导致数据依然是离开的状态不会初始化

新功能的实现:

https://github.com/HelloZJW/mpvue-page-factory 不知官方能否参照他的实现思路来解决。自己使用这个库确实可以解决这个问题,但是由于是第三方维护,怕后期会跟官方的更新产生冲突

相关项目或文档:

https://github.com/HelloZJW/mpvue-page-factory

@some-code
Copy link

hack.js

const pageDatas = {}

export default {
  install(_Vue) {
    // 添加全局方法或属性
    _Vue.prototype.$isPage = function isPage() {
      return this.$mp && this.$mp.mpType === 'page'
    }

    _Vue.prototype.$pageId = function pageId() {
      let pid = null
      try {
        pid = this.$isPage() ? this.$mp.page.__wxWebviewId__ : null
      } catch (e) { }
      return pid
    }

    // 注入组件
    _Vue.mixin({

      methods: {
        stashPageData() {
          return { data: { ...this.$data } }
        },
        restorePageData(oldData) {
          Object.assign(this.$data, oldData.data)
        },
      },

      onLoad() {
        if (this.$isPage()) {
          // 新进入页面
          Object.assign(this.$data, this.$options.data())
        }
      },

      onUnload() {
        if (this.$isPage()) {
          // 退出页面,删除数据
          delete pageDatas[this.$pageId()]
          this.$needReloadPageData = true
          this._watchers = [];
        }
      },

      onHide() {
        if (this.$isPage()) {
          // 将要隐藏时,备份数据
          pageDatas[this.$pageId()] = this.stashPageData()
        }
      },

      onError(err) {
        console.error(err);
      },

      onShow() {
        if (this.$isPage()) {
          // 如果是后退回来的,拿出历史数据来设置data
          if (this.$needReloadPageData) {
            const oldData = pageDatas[this.$pageId()]
            if (oldData) {
              this.restorePageData(oldData)
            }
            this.$needReloadPageData = false
          }
        }
      },

    })
  },
}

main.js

import Vue from 'vue'
import Hack from './utils/hack'
Vue.use(Hack)

@zxzhgk
Copy link
Author

zxzhgk commented Dec 28, 2018

@some-code 谢谢~ 我去试下

@zxzhgk
Copy link
Author

zxzhgk commented Dec 28, 2018

他解决方式修改了 mpvue-loader ,担心会跟官方的更新产生冲突

@zxzhgk zxzhgk closed this as completed Dec 29, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants