vue2 mixins and vue3 hooks

  • vue2 mixins and vue3 hooks
  • vue2 mixins
    • vue2 mixins hook function
    • How to use Mixins in vue2
  • vue3 hooks
    • What are hooks
    • how to use

vue2 mixins and vue3 hooks

Mixins in Vue.js 2.x and Composition API (including hooks) in Vue.js 3.x are two different code organization and reuse mechanisms.

  1. Vue.js 2.x Mixins:

    • Mixins are a way to inject reusable functionality and logic into components.
    • Use mixins to encapsulate some common options (such as life cycle hooks, data, methods, etc.) into objects and then mix them into multiple components.
    • By introducing mixins objects into the mixins array of component options, options in mixins can be merged into the component.
    • The options in Mixins will be merged with the options of the component itself. If there is a conflict, it will be handled according to certain strategies.
    • The disadvantage of mixins is that they can lead to naming conflicts and namespace pollution.
  2. Vue.js 3.x Composition API (Hooks):

    • Composition API is a set of functional API introduced in Vue.js 3.x, which is used to organize and reuse component logic more flexibly.
    • Using the Composition API, we can encapsulate relevant logic by creating custom logic blocks (i.e. composition functions) and apply them to one or more components.
    • The Composition API uses some new functions, such as ref, reactive, watch, etc., as well as the new hook function setup to define component logic.
    • Hooks can aggregate related logic together to improve code readability and maintainability.
    • The advantage of the Composition API is that it can organize and reuse logic more flexibly, avoiding the problems of naming conflicts and namespace pollution.

It should be noted that the Composition API of Vue.js 3.x is incompatible with the mixins of Vue.js 2.x.

If you are migrating a project or choosing to develop a new project, you can choose the appropriate version and mechanism based on your specific needs and team familiarity.

At the same time, the Composition API of Vue.js 3.x provides more powerful capabilities and a better development experience, and is recommended for use in new projects.

vue2 mixins

vue2 mixins hook function

In Vue.js 2.x mixins, you can use the following hook functions to define and handle the life cycle of components:

  1. created: Called after the component instance is created, often used for data initialization or non-responsive operations.
  2. mounted: Called after the component is mounted on the DOM. It is often used for DOM-related operations and initialization.
  3. updated: Called after the component is updated. This hook function will be triggered when the data of the component changes and causes re-rendering.
  4. beforeDestroy: Called before the component is destroyed, some cleanup operations can be performed, such as unsubscribing, unbinding events, etc.
  5. destroyed: Called after the component is destroyed to perform some cleanup and resource release operations.

In addition to the above-mentioned commonly used hook functions, there are other hook functions available, such as beforeCreate, beforeMount, etc. These hook functions can be mixed into components through mixins to achieve the same logic reuse.

The steps to define hook functions using mixins are as follows:

  1. Create a mixins object containing hook functions and other options.
  2. Introduce mixins objects into the mixins array in the component.
  3. When the component’s life cycle is triggered, the corresponding hook function in the mixins will also be called.

It should be noted that if the hook functions in multiple mixins objects have the same name, they will be called sequentially in the order of the mixins array.

Sample code looks like this:

//Create a mixins object
var myMixin = {<!-- -->
  created: function () {<!-- -->
    console.log('Mixin created');
  },
  mounted: function () {<!-- -->
    console.log('Mixin mounted');
  }
};

//Introduce mixins objects into components
new Vue({<!-- -->
  mixins: [myMixin],
  created: function () {<!-- -->
    console.log('Component created');
  },
  mounted: function () {<!-- -->
    console.log('Component mounted');
  }
});

In the above code, when a Vue instance is created, the created and mounted hook functions will be called sequentially in the order of mixins, and then the component’s own hook function will be called.

How to use Vue2’s Mixins

Vue2’s Mixins can be used to combine logic shared among multiple components, making code reuse simpler and improving development efficiency. The steps to use Mixins are as follows:

  1. Create a mixin file containing common logic.
export const mixin = {<!-- -->
  data() {<!-- -->
    return {<!-- -->
      message: 'Hello, world!'
    }
  },
  methods: {<!-- -->
    showMessage() {<!-- -->
      alert(this.message);
    }
  }
}
  1. Introduce and use Mixins in components that need to use Mixins.
import {<!-- --> mixin } from './mixin.js';
export default {<!-- -->
  mixins: [mixin],
  mounted() {<!-- -->
    this.showMessage(); // Output: "Hello, world!"
  }
}

You need to pay attention to the following when using Mixins:

  • The properties and methods defined by Mixins will be merged into the component. In case of conflict, the component will take precedence.

  • Mixins can be used by multiple components. If Mixins is referenced by multiple components, its data and methods will be mixed. You need to pay attention when using them in components.

  • Do not modify the data or state of the Vue instance in Mixins. The data and methods of Mixins may conflict with the data and methods of the component.

  • Hook functions in mixins will be executed before hook functions in components.

vue3 hooks

What are hooks

Hook means hook. When you see “hook”, do you think of hook function? In fact, hooks are really a way of writing functions.

vue3 developed the Composition API based on react hooks, so it means that the Composition API can also be customized to encapsulate hooks.

Hooks in vue3 is a way of writing functions, which is to extract the js code of some individual functions of the file and put it into a separate js file, or some public methods/functions that can be reused< /strong>.

In fact, hooks are somewhat similar to mixins in vue2, but compared to mixins, hooks are clearer about the source of reused function code and are clearer and easier to understand.

How to use

In Vue 3, you can use Hooks in the Composition API to achieve code reuse. Here are some common methods:

  1. Custom Hooks function: You can write a custom Hooks function, encapsulate some common logic into the function, and then reference it in multiple components. For example, you can create a custom Hooks function named useValidation for reuse of form validation logic.
// useValidation.js
import {<!-- --> ref } from 'vue';

export function useValidation() {<!-- -->
  const error = ref(null);

  function validate(value) {<!-- -->
    if (!value) {<!-- -->
      error.value = 'Field is required';
    } else {<!-- -->
      error.value = null;
    }
  }

  return {<!-- -->
    error,
    validate,
  };
}

Then, use this Hooks function in the component that requires form validation:

import {<!-- --> useValidation } from './useValidation';

export default {<!-- -->
  setup() {<!-- -->
    const {<!-- --> error, validate } = useValidation();

    function onSubmit() {<!-- -->
      // authenticating
      validate(value);
      
      if (error.value) {<!-- -->
        //Display error message
      } else {<!-- -->
        // submit Form
      }
    }

    return {<!-- -->
      error,
      onSubmit,
    };
  },
};
  1. Public logic extraction: Use Composition API Hooks to extract public logic and pass it as parameters to other Hooks. This way multiple components can share the same logic.
import {<!-- --> ref, watchEffect } from 'vue';

export function useFetchData(url) {<!-- -->
  const data = ref(null);
  const loading = ref(false);
  const error = ref(null);

  watchEffect(() => {<!-- -->
    loading.value = true;

    fetch(url)
      .then(response => response.json())
      .then(result => {<!-- -->
        data.value = result;
        loading.value = false;
      })
      .catch(err => {<!-- -->
        error.value = err;
        loading.value = false;
      });
  });

  return {<!-- -->
    data,
    loading,
    error,
  };
}

Then, use this Hooks function in the component that needs to get the data:

import {<!-- --> useFetchData } from './useFetchData';

export default {<!-- -->
  setup() {<!-- -->
    const {<!-- --> data, loading, error } = useFetchData('https://api.example.com/data');

    return {<!-- -->
      data,
      loading,
      error,
    };
  },
};

In this way, you can encapsulate some commonly used logic and reuse it in multiple components, improving the maintainability and reusability of the code.

syntaxbug.com © 2021 All Rights Reserved.