Vue.js:您和第三方组件的生命周期挂钩


生命周期挂钩是任何组件的重要组成部分。 我们,我们的应用程序,通常需要知道在创建,安装,更新或销毁组件时会发生什么情况。

在组件中,我们可以使用适当的方法来捕获这些事件,例如:

  • created-创建了组件实例
  • 已安装 -组件实例已安装
  • 更新 -由于数据更改,虚拟DOM已更新
  • destroy-组件实例被销毁
  • 该文件

在我们组件的代码中,它将如下所示:

// MyComponent.vue <template> <h1>Hello, {{ who }}</h1> </template> <script> export default { name: 'MyComponent', data() { return { who: 'world' } }, mounted() { //  -      } } </script> 

好啊 但是,如果父组件需要知道子组件中发生了什么,例如该组件已更新,该怎么办? 在子组件中,我们可以引发一个事件,并将侦听器挂在父组件上。 在我们应用程序的代码中,它将如下所示:

 //   ChildComponent.vue <template> <div> <div>Count: {{ counter }}</div> <button @click="add">+1</button> </div> </template> <script> export default { name: 'ChildComponent', data() { return { counter: 0 } }, updated() { this.$emit('updated') }, methods: { add() { this.counter++ } } } </script> 

 //   ParentComponent.vue <template> <div> <ChildComponent @updated="usefulMethod"/> </div> </template> <script> import ChildComponent from 'ChildComponent.vue' export default { name: 'ParentComponent', components: { ChildComponent }, data() { return {} }, methods: { usefulMethod() { //  -        } } } </script> 

太好了,当更新子组件时,父组件会捕获已更新的事件,并执行有用的方法()方法。

一切都很酷! 但是,如果我们需要嵌入从npm或git下载的第三方组件,并在父组件中做一些有用的事情,例如在安装时,该怎么办? 在挂接的钩子中进入第三方组件的代码,以生成事件...这不是一个好主意! 但是,如果我告诉您不必这样做怎么办! 相反,我们只能听事件! 该事件的名称将是生命周期挂钩的名称,但是您需要在其上添加@hook:前缀@hook:类似@hook:___ ,例如: @hook:mounted, @hook:updated @hook:destroyed

在代码中,它将如下所示:

 //   ParentComponent.vue <template> <div> <ThirdPartyComponent @hook:mounted="usefulMethod"/> </div> </template> <script> import ThirdPartyComponent from 'vue-third-party-component' //   export default { name: 'ParentComponent', components: { ThirdPartyComponent }, data() { return {} }, methods: { usefulMethod() { //  -    mounted     } } } </script> 

在我看来,这对于使用其自己的组件和第三方组件都是非常有用的功能。 希望您会发现它有用。 奇怪的是,文档中对此一言不发,只有阅读源代码才能找到某些功能。

感谢您的阅读。 阅读基座和源代码! 随着即将到来的2020年新年!

Source: https://habr.com/ru/post/zh-CN482030/


All Articles