Home > Web Front-end > Vue.js > body text

Learn the combined API in Vue 3 to better organize and manage component code

王林
Release: 2023-09-09 08:45:56
Original
1185 people have browsed it

学习Vue 3中的组合式API,更好地组织和管理组件代码

Learn the combined API in Vue 3 to better organize and manage component code

Vue 3 is the latest version of the Vue framework, which introduces many commands There are exciting new features and improvements, the most notable of which is the composition API. Composable APIs enable us to better organize and manage component code, and better reuse and share logic.

In Vue 2, we use the Options API to define and organize components. Each component contains an options object, which contains the component's data, methods, life cycle hooks, etc. This approach can lead to confusing code that is difficult to maintain and test when the components are large and complex. Vue 3's composed API provides a more concise, flexible and composable way to write components.

1. Basic usage
The combined API is based on functions and organizes logic through "composition". We can split the component logic into smaller functions and then combine these functions to build the component.

import { reactive, computed } from 'vue';

export default {
  setup() {
    // 响应式数据
    const state = reactive({
      count: 0,
    });

    // 计算属性
    const double = computed(() => state.count * 2);

    // 方法
    const increment = () => {
      state.count++;
    };

    return {
      state,
      double,
      increment,
    };
  },
};
Copy after login

In this example, we use the setup function to set up the logic of the component. The setup function is a special function that will be called before the component is created. We can define reactive data, calculated properties and methods in the setup function and use them as return values.

In the above code, we use the reactive function to create a responsive state object, which contains a count attribute. We also define a computed property double using the computed function, which multiplies the value of the count property by 2. Finally, we define an increment method to increase the value of the count attribute. In the return value of the setup function, we export state, double, and increment as properties.

2. Logic reuse
Using the combined API, we can more easily implement logic reuse. We can extract some commonly used logic into custom Hooks and reuse them in multiple components.

// useCounter.js
import { reactive } from 'vue';

export default function useCounter(initialValue) {
  const state = reactive({
    count: initialValue,
  });

  const increment = () => {
    state.count++;
  };

  const decrement = () => {
    state.count--;
  };

  return {
    state,
    increment,
    decrement,
  };
}

// ComponentA.vue
import { computed } from 'vue';
import useCounter from './useCounter';

export default {
  setup() {
    const { state, increment, decrement } = useCounter(0);
    const double = computed(() => state.count * 2);

    // ...

    return {
      state,
      double,
      increment,
      decrement,
    };
  },
};

// ComponentB.vue
import { computed } from 'vue';
import useCounter from './useCounter';

export default {
  setup() {
    const { state, increment, decrement } = useCounter(100);
    const half = computed(() => state.count / 2);

    // ...

    return {
      state,
      half,
      increment,
      decrement,
    };
  },
};
Copy after login

In this example, we created a custom HookuseCounter to handle the counting logic. useCounterThe function accepts an initial value as a parameter and returns an object containing reactive data and methods. We can call the useCounter function in any component that requires counting logic and use the properties in the return value.

In ComponentA.vue and ComponentB.vue, we used different initial values ​​to call the useCounter function, and used the return properties to implement different calculation logic.

3. Use in combination with other APIs
The combined API can be flexibly combined with other APIs of Vue, such as life cycle hooks, custom instructions, etc., allowing us to better control the components. Behavior.

import { ref, onMounted, onBeforeUnmount } from 'vue';

export default {
  setup() {
    const count = ref(0);

    const increment = () => {
      count.value++;
    };

    // 组件挂载时触发
    onMounted(() => {
      console.log('Component is mounted');
    });

    // 组件卸载前触发
    onBeforeUnmount(() => {
      console.log('Component is about to be unmounted');
    });

    // ...

    return {
      count,
      increment,
    };
  },
};
Copy after login

In this example, we use the ref function to create a responsive count variable and define an increment method to increase the value of count. We also use the onMounted hook and the onBeforeUnmount hook to perform corresponding operations when the component is mounted and unmounted.

The combined API gives us a more flexible, composable and testable way to organize and manage component code. By splitting logic and reusing it, we can better improve the readability, maintainability and scalability of the code. If you haven’t tried Vue 3’s composable API yet, now is a great time!

The above is the detailed content of Learn the combined API in Vue 3 to better organize and manage component code. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template