Are you still using the Options API?


foreword

The emergence of the combined API now directly solves the problems and pain points of the Options Api (options)


1. Options API (Optional)

I believe you are familiar with the writing of the following code.
The main function is to build a todoList with elementui. It is very simple. If you expand the function of changing the status later, add pop-up window verification, add data input verification, add submission success notification and other functions. The code will get longer and longer. Difficult to maintain later.

<template>
  <div style="width: 800px">
    <el-row>
      <el-col :span="19">
        <el-input v-model="input" placeholder="Please input" />
      </el-col>
      <el-col :span="4">
        <el-button @click="addItem" type="primary">Add</el-button>
      </el-col>
    </el-row>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column fixed prop="date" label="Date" />
      <el-table-column prop="name" label="Item" />
      <el-table-column prop="state" label="State" />
      <el-table-column fixed="right" label="Operations">
        <template #default="scope">
          <el-button
            link
            type="primary"
            size="small"
            @click="remove(scope.$index)"
          >
            delete
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script lang="ts">
import {
    
     defineComponent, reactive, ref } from "vue";
type tableDataType = {
    
    
  id: number;
  date: string;
  name: string;
  state: string;
};
export default defineComponent({
    
    
  setup() {
    
    
    const input = ref("");
    const tableData = reactive<tableDataType[]>([]);
    return {
    
    
      input,
      tableData,
    };
  },
  methods: {
    
    
    remove(index: number) {
    
    
      this.tableData.splice(index, 1);
    },
    addItem() {
    
    
      console.log(this.tableData);
      this.tableData.push({
    
    
        id: Math.random(),
        date: new Date().toLocaleString(),
        name: this.input,
        state: "Y",
      });
      this.input = "";
    },
  },
});
</script>

2. Composition API (combined)

Use the combined writing method. If you expand the input box function later, you can put all the changes related to the input box into a content block. For example, the validation function is extended on the input box below. After adding other methods related to the input box, you can continue to write together

<script lang="ts" setup>
import {
    
     reactive, ref } from "vue";
type tableDataType = {
    
    
  id: number;
  date: string;
  name: string;
  state: string;
};

const input = ref("");
const inputFn = (value: string) => {
    
    
  switch (value) {
    
    
    case "1":
      window.alert("Already exists");
      break;
    case "2":
      window.alert("error");
      break;
    default:
      break;
  }
};

const tableData = reactive<tableDataType[]>([]);
const remove = (index: number) => {
    
    
  tableData.splice(index, 1);
};
const addItem = () => {
    
    
  console.log(tableData);
  tableData.push({
    
    
    id: Math.random(),
    date: new Date().toLocaleString(),
    name: input.value,
    state: "Y",
  });
  input.value = "";
};
</script>

3. Advantages

1. It is very intuitive like the above example, which can be better maintained and expanded later. Code is more readable.
2. The combined API solves all the shortcomings of mixins

Unclear data source: When multiple mixins are used, it becomes unclear which mixin the data attribute on the instance comes from, and it takes a long time to find it.

Namespace conflicts: Multiple mixins from different authors may register the same property name, causing naming conflicts. With composite functions, you can avoid identical key names by renaming variables when destructuring them.

Implicit cross-mixin communication: multiple mixins need to rely on shared property names to interact, which makes them implicitly coupled together. And the return value of a composite function can be passed as an argument to another composite function, just like ordinary functions.

3. Smaller production package size​

Combination APIs are more efficient and friendly to code compression than <script setup>the equivalent option APIs. This is because <script setup>the component template written in the form is compiled into an inline function, which <script setup>is in the same scope as the code in . Unlike the optional API
which needs to rely on the this context object to access properties, the compiled template can directly access <script setup>the variables defined in it without proxying from the instance. This is more compression-friendly, because local variable names can be compressed, but object property names cannot.

4. Better type inference

The compositional API primarily utilizes basic variables and functions, which are inherently type-friendly. Code rewritten with a combined API can enjoy complete type deduction without writing too many type annotations.

4. Disadvantages

  1. High learning cost: Compared with the optional API in Vue2, the combined API needs to learn some new APIs and organize the overall structure of the code by yourself, unlike Vue2, which helps you plan code modules. But I don't think that's a disadvantage

  2. Responsiveness needs to be managed manually: Responsiveness needs to be managed manually in the composite API, and APIs such as ref and reactive need to be used to create responsive data.

Summarize

1. In terms of logical organization and logical reuse, Composition API is superior to Options API.
2. Composition API will have better type inference.
3. Composition API is friendly to tree-shaking, and the code is easier to compress.
4. There is no this in the Composition API, which reduces the situation where this points to unknown.
5. If it is a small component, of course you can continue to use the Options API.
6. And the official will not abandon the Options API.

References: Vue Official Documentation

Guess you like

Origin blog.csdn.net/qq_43205326/article/details/129918529