IT이야기

Vue 라이프 사이클 훅 확장

cyworld 2022. 6. 13. 22:30
반응형

Vue 라이프 사이클 훅 확장

탑재 시 모든 컴포넌트에 대해 메서드를 실행하고 싶은 특별한 어플리케이션이 있습니다.그래서 글로벌 믹스인 같은 방법으로 간단하게 할 수 있습니다.

mounted(){
   this.mySpecialMethod();
}

단, Vues 마운트 훅만 연장하여 마운트 시 항상 모든 컴포넌트에서 실행할 수 있는지 궁금합니다.나는 이것에 대한 정보를 찾을 수 없었다.

정말 모든 걸 다 하고 싶다면mounted훅은 글로벌 믹스인을 사용할 수 있습니다.

아래에는 믹스인이 있습니다.myMixin설치 또는 파괴될 때마다 콘솔에 기록됩니다.예를 실행하면 더하기 버튼을 클릭할 때마다 두 구성 요소 모두 실행됩니다.mounted훅과 믹스인의 훅이 있습니다.

라이브러리로 재사용할 수 있도록 이 기능을 확장하려면 이 기능을 사용하여 플러그인을 생성할 수 있습니다.

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>

언급URL : https://stackoverflow.com/questions/50876597/extending-vue-lifecycle-hooks

반응형