본문 바로가기
Web/JavaScript

[Vue3] Mixins

by llHoYall 2021. 6. 26.

Mixin is a method of implementing functions separately and combining mixin files into components whenever necessary.

 Create a Project

2021.06.02 - [Web/JavaScript] - [Vue3] Getting Started with Vue3 + TypeScript + TailwindCSS

Let's create a project to start to learn Mixin. 

Create Mixins

mixins/mixin.ts

export default {
  methods: {
    $callMixin(name: string): string {
      return `Hello, ${name}`;
    },
  },
};

Created a simple example.

This mixin example has one function that takes a name and returns a message.

$ is for preventing duplication of a name.

Use Mixins

components/mixin.vue

<template>
  <div class="p-4 flex flex-col justify-start items-center">
    <h2 class="mt-8 mb-2 text-xl font-medium text-green-600">Mixin</h2>
    <div class="flex items-center">
      <div>Name</div>
      <input
        type="text"
        v-model="name"
        class="ml-4 px-2 py-1 rounded text-gray-700"
      />
      <button @click="useMixin" class="btn ml-4">Use Mixin</button>
    </div>
    <div class="mt-2">{{ result }}</div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import hMixin from "../mixins/mixin";

export default defineComponent({
  name: "Mixin",
  mixins: [hMixin],
  data() {
    return { 
      name: "", 
      result: "" 
    };
  },
  methods: {
    useMixin: function () {
      this.result = this.$callMixin(this.name);
    },
  },
});
</script>

Imported our mixin name as hMixin and added it into mixins property.

Now, we can use it with this.

It's rendering time!

 

App.vue

<template>
  <div class="my-4 flex justify-center items-center">
    <Mixin />
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import Mixin from "./components/mixin.vue";

export default defineComponent({
  name: "App",
  components: {
    Mixin,
  },
});
</script>

I'm happy with this!

Mixins with Lifecycle Hooks

Let's add lifecycle hooks in our mixin.

export default {
  methods: {
    $callMixin(name: string): string {
      return `Hello, ${name}`;
    },
  },
  beforeMount(): void {
    console.log("beforeMount in mixin");
  },
  mounted(): void {
    console.log("mounted in mixin");
  },
  beforeUnmount(): void {
    console.log("beforeMount in mixin");
  },
  unmounted(): void {
    console.log("unmounted in mixin");
  },
};

Conclusion

Now, we can know about the Mixin in Vue3.

'Web > JavaScript' 카테고리의 다른 글

[Vue3] Getting Started with Vue3 + Electron (with Typescript, TailwindCSS)  (0) 2021.06.28
[Vue3] Vuex Usage  (0) 2021.06.26
[Vue3] Composition API  (0) 2021.06.25
[vue3] Plugins  (0) 2021.06.25
[Vue3] Custom Directives  (0) 2021.06.24

댓글