扩展 Vue 生命周期钩子 [英] Extending Vue Lifecycle Hooks

查看:54
本文介绍了扩展 Vue 生命周期钩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个特殊的应用程序,我想在安装它时在每个组件上运行一个方法.所以我可以将该方法作为全局混合或其他东西,然后简单地做..

mounted(){this.mySpecialMethod();}

但是,我想知道是否可以简单地扩展 Vues 挂载钩子,以便在挂载时始终在每个组件上运行该方法.我一直无法在这方面的信息中找到.

解决方案

如果你真的想让所有东西都调用你的 mounted 钩子,你可以使用 全局混合.

下面,我们有 mixin myMixin 每次挂载或销毁某些东西时都会记录到控制台.运行示例时,您可以看到每次点击加号按钮时,它都会运行组件的 mounted 钩子以及 mixin 的钩子.

如果你想扩展它以便它可以作为一个库重用,你可以创建一个 插件出来.

const foo = {模板:<div @click='onClick'>你好</div>",安装(){console.log("Foo 挂载了");},方法: {点击(){console.log("点击");}}}const myMixin = {安装(){console.log("我已经挂载了");},销毁(){console.log("我已经被摧毁了");}};Vue.mixin(myMixin);const app = new Vue({el: "#app",数据() {返回 {福斯:[]};},成分: {富},方法: {添加() {this.foos.push("嘶嘶声");},消除() {this.foos.pop();}}});

<script src="https://cdn.jsdelivr.net/npm/vue"></script><div id="应用程序"><button @click="add()">+</button><button @click="remove()">-</button><ul><li v-for="f in foos"><foo></foo>

I have a special application where I would like to run a method on every component when it is mounted. So I could have the method as a global mixin or something and then simply do..

mounted(){
   this.mySpecialMethod();
}

However, I was wondering if it is possible to simply extend Vues mounted hook so the method is always run on every component when it is mounted. I have not been able to find in info on this.

解决方案

If you really want to have everything call your mounted hook, you can use a global mixin.

Below, we have the mixin myMixin that will log to console every time something is mounted or destroyed. When you run the example, you can see that every time the plus button is clicked, it runs both the component's mounted hook as well as the mixin's hook.

If you want to extend this so that it can be reusable as a library, you can create a plugin out of it.

const foo = {
  template: "<div @click='onClick'>hello</div>",
  mounted() {
    console.log("Foo's mounted");
  },
  methods: {
    onClick() {
      console.log("click");
    }
  }
}

const myMixin = {
  mounted() {
    console.log("I've been mounted");
  },
  destroyed() {
    console.log("I've been destroyed");
  }
};

Vue.mixin(myMixin);

const app = new Vue({
  el: "#app",
  data() {
    return {
      foos: []
    };
  },
  components: {
    foo
  },
  methods: {
    add() {
      this.foos.push("fizz");
    },
    remove() {
      this.foos.pop();
    }
  }
});

<script src="https://cdn.jsdelivr.net/npm/vue"></script>

<div id="app">
  <button @click="add()">+</button><button @click="remove()">-</button>
  <ul>
    <li v-for="f in foos">
      <foo></foo>
  </ul>
</div>

这篇关于扩展 Vue 生命周期钩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆