简体   繁体   English

使用 Vue 和 webpack 钩住 HMR

[英]Hook for HMR with Vue & webpack

Is there any option to set up hook when some of Vue component were updated with hot module replacement?当某些 Vue 组件通过热模块替换更新时,是否有设置挂钩的选项?

[HMR] App is up to date.

And now I would like to call some method.现在我想调用一些方法。

Searching through webpack HMR I have found two methods: dispose and removeDisposeHandler .通过 webpack HMR 搜索我发现了两种方法: disposeremoveDisposeHandler

dispose处置

Add a handler which is executed when the current module code is replaced.添加在替换当前模块代码时执行的处理程序。 This should be used to remove any persistent resource you have claimed or created.这应该用于删除您声明或创建的任何持久资源。 If you want to transfer state to the updated module, add it to the given data parameter .如果要将状态传输到更新的模块,请将其添加到给定的data parameter This object will be available at module.hot.data after the update.更新module.hot.data after ,此对象将在module.hot.data after可用。

removeDisposeHandler移除处理程序

Remove the handler added via dispose or addDisposeHandler .删除通过 dispose 或addDisposeHandler添加的处理程序。

So I added dispose in created hook and removed it in destroyed hook like this:所以我在created钩子中添加了dispose并在destroyed钩子中删除了它,如下所示:

export default {
  methods: {
    callback(data) {
      console.log(data)
    },
  },
  created() {
    if (module.hot) {
      module.hot.dispose(this.callback)
    } 
  },
  destroyed() {
    if (module.hot) {
      module.hot.removeDisposeHandler(this.callback)
    }
  },
}

I have tested it in my Vue CLI app and everything works perfectly: it invokes when exactly this module is changed, but does not when another.我已经在我的 Vue CLI 应用程序中对其进行了测试,一切正常:它在此模块发生更改时调用,但在另一个模块更改时不调用。

@Javas, thanks for hint. @Javas,感谢提示。 Solution that I'm looking for is:我正在寻找的解决方案是:

module.hot.addStatusHandler(status => {
    console.log('module hot status', status)
});

I placed it into my entry file and it's called each time if any of components are hot-reloaded.我将它放入我的入口文件中,如果任何组件被热重载,则每次都会调用它。

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

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