SoFunction
Updated on 2025-04-04

Introduction to the difference and use of Vue OptionsAPI and CompositionAPI

The difference between OptionsAPI and CompositionAPI in code usage and logic

1. Differences in code usage

(I) Component definition structure

  • OptionsAPI
    • Define components in the form of object literals. The object contains multiple properties, each attribute corresponding to a different function. For example:
export default {
  data() {
    return {
      message: 'Hello, OptionsAPI'
    };
  },
  methods: {
    sayHello() {
      ();
    }
  },
  mounted() {
    ();
  }
};
  • heredatamethodsmountedThe attributes of the component define the data, methods, life cycle hooks, etc., which exist independently of each other under a large object structure.
  • CompositionAPI
    • usesetupFunctions act as the entry point of component logic, define various logics inside the function and return values ​​for use by the template. For example:
import { ref } from 'vue';
export default {
  setup() {
    const message = ref('Hello, CompositionAPI');
    const sayHello = () => {
      ();
    };
    sayHello();
    return {
      message,
      sayHello
    };
  }
};
  • existsetupIn the function, responsive data (such asrefThe created data), methods, etc. are logically compactly combined, and then the data and methods that need to be used in the template are exposed by returning values.

(II) Definition and use of responsive data

OptionsAPI

  • existdataDefine responsive data in the function. For example:
export default {
  data() {
    return {
      count: 0
    };
  },
  methods: {
    increment() {
      ++;
    }
  }
};
  • Responsive data passesthisThe keywords aremethodswatchetc. access and modify it in other properties. HerethisPoint to component instances, this method may occur when used in multi-layer nested functions or callback functionsthisPoint to confusion.
    • CompositionAPI
  • usereforreactiveFunctions to define responsive data.
  • For exampleref
import { ref } from 'vue';
export default {
  setup() {
    const count = ref(0);
    const increment = () => {
      ++;
    };
    return {
      count,
      increment
    };
  }
};
  • Or usereactive(Used to create responsive data of object type):
import { reactive } from 'vue';
export default {
  setup() {
    const state = reactive({
      count: 0
    });
    const increment = () => {
      ++;
    };
    return {
      state,
      increment
    };
  };
};
  • Responsive data passesvalueproperty(refType) or directly manipulate object properties (reactiveType) to access and modify, avoidingthisPoint to the problem.

(III) Implementation of logical multiplexing

  • OptionsAPI
    • Mainly bymixinsto implement logical multiplexing. For example, create amixinObject:
const myMixin = {
  data() {
    return {
      sharedData: 'This is shared data'
    };
  },
  methods: {
    sharedMethod() {
      ('This is a shared method');
    }
  }
};
export default {
  mixins: [myMixin],
  // Other logic of the component itself  data() {
    return {
      componentData: 'This is component - specific data'
    };
  },
  mounted() {
    ();
  }
};

butmixinsThere are some problems such as possible naming conflicts (if multiplemixinsThere are attributes or methods with the same name) and when used in components, it is difficult to trace the origin of a certain attribute or method.

  • CompositionAPI
    • Logical multiplexing is achieved through custom combination functions.

For example:

import { ref } from 'vue';
const useCounter = () => {
  const count = ref(0);
  const increment = () => {
    ++;
  };
  return {
    count,
    increment
  };
};
export default {
  setup() {
    const { count, increment } = useCounter();
    return {
      count,
      increment
    };
  }
};
  • Custom combinatorial functions can be reused in multiple components, with clear code structure and easy to understand and maintain.

2. Logical differences

(I) Logical cohesion

  • OptionsAPI
    • Related logic is scattered in different option properties. For example, the initialization logic associated with a data might be indataIn the operation logic of the data ismethodsIn the data change listening logic iswatchmiddle. This dispersed structure makes it necessary to switch between multiple attributes to understand the complete logical flow when dealing with complex functions.
  • CompositionAPI
    • existsetupRelevant logic can be combined in functions. For example, for a counter function, it can besetupThe function defines responsive data, methods of operating data, and related life cycle hooks (if needed), making the logic of the entire function more cohesive and easy to understand and maintain.

(II) Support logic for Type-Script

  • OptionsAPI
    • When using TypeScript in OptionsAPI, you need to define the type separately for each option attribute. For example,dataThe data defined in the function needs to be defined separately.methodsThe methods in this article also need to define the parameters and return values, etc. This makes the type definition scattered throughout the component definition and the code structure is relatively complex.
    • Here is an example of OptionsAPI using TypeScript:
export default {
  data(): {
    message: string;
  } {
    return {
      message: 'Hello'
    };
  },
  methods: {
    sayHello(): void {
      ();
    }
  }
};
  • CompositionAPI
    • Since logic is organized in a functional form,setupThe overall type definition can be more convenient in the function. OKsetupThe input parameters and return values ​​of the function are type-defined, and the types can be well defined in custom combination functions. This method is more closely integrated with TypeScript's function type system, and the type definition of the code is more concise and clear.
    • For example:
import { ref } from 'vue';
const useCounter = (): {
  count: { value: number };
  increment: () => void;
} => {
  const count = ref(0);
  const increment = () => {
    ++;
  };
  return {
    count,
    increment
  };
};
export default {
  setup(): {
    count: { value: number };
    increment: () => void;
  } {
    const { count, increment } = useCounter();
    return {
      count,
      increment
    };
  }
};

This is the end of this article about the difference between Vue OptionsAPI and CompositionAPI. For more related contents of Vue OptionsAPI and CompositionAPI, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!