SoFunction
Updated on 2025-04-03

Vue3 combined with TypeScript project development practical records

Overview

Vue3 has been out for a while, and has carried out a lot of business practices in the team and has also thought about it.

In general, Vue3 has made great progress in both the underlying principles and the actual business development.

Using proxy instead of the previous API has better performance and also solved the previous defects of vue in processing objects and arrays; in the diff algorithm, static marking is used, which greatly improves Vue's execution efficiency.

At the level of use, we have changed from options API to composition API. In actual business, we have abandoned the original isolated writing methods of data, methods, and computed. compasiton API, it focuses more on the aggregation of related businesses. At the same time, in the composition API, in order to prevent excessive business logic, it provides a way to separate the focus, greatly improving the readability of our code.

TypeScript is fully supported, and type verification has also become the quality assurance for Vue3 to carry out large-scale project development in the future. At the same time, this is also towards the trend - the future of the front-end is TypeScript!

1、compositon Api

The essence of the compasiton API is reflected in the code, which is a setup function. In this setup function, the returned data will be used in the template of the component. The return object, to a certain extent, represents the data attribute in vue2 before.

import { defineComponent, ref } from 'vue';
export default defineComponent({
    name: 'Gift',
    setup() {
        const counter = ref(0);
        return {
            counter
        }
    }
})

At this time, for most beginners, the possible doubt is, can I define the writing method of options API, such as data, computed, watch, methods, etc.

What I need to be clear here is that Vue3 is fully compatible with the writing of this option API of Vue2, but from a conceptual perspective, it is more recommended to write our components by setting. The reason is as follows: Vue3 exists itself to solve the problem of Vue2. The problem of Vue2 is that insufficient aggregation will lead to the code becoming more and more bloated! The setup method can make data, method logic, dependencies, etc. aggregate together, making it more convenient to maintain.

In other words, in the future, we try not to write separate data, computed, watch, methods, etc. It is not that Vue3 does not support it, but it is contrary to Vue3's concept.

The components attribute is a subcomponent of a component. The configuration is not much different from Vue2 and 3. How to use Vue2, Vue3 is still used like that.

1. What is the difference between ref and reactive?

In terms of functionality, both ref and reactive can implement responsive data!

At the grammatical level, the two are different. Reactive data defined by ref needs to be changed in the form of [data].value; data defined by reactive needs to be changed in the form of [data].[prpoerty].

const actTitle: Ref<string> = ref('Activity Name');

const actData = reactive({
    list: [],
    total: 0,
    curentPage: 1,
    pageSize: 10
});

 = 'Activity Name 2';

 = 100;

However, there are still differences at the application level. Generally speaking, we use ref to define the responsive formula for a single normal type of data. In a form scenario, a scene that describes an object like key:value of a form, uses reactive; in some scenarios, a set of data for a certain module is usually used to define data in a reactive way.

So, do objects have to be defined using reactive? Actually, it’s not possible, you can analyze the specific problems according to your business scenario! ref He emphasizes the change of a data value, while reactive emphasizes the change of a certain property of the defined object.

2. Periodic function

Periodic functions, in Vue3, are used separately and are used as follows:

import { defineComponent, ref, onMounted } from 'vue';
export default defineComponent({
    name: 'Gift',
    setup() {
        const counter = ref(0);
        onMounted(() => {
            // Process business, generally conduct data requests        })
        return {
            counter
        }
    }
})

3. Store use

In Vue2, you can actually get it directly through this.$store, but in Vue3, there is actually no concept of this, and the usage is as follows:

import { useStore } from "vuex";
import { defineComponent, ref, computed } from 'vue';
export default defineComponent({
    name: 'Gift',
    setup() {
        const counter = ref(0);
        const store = useStore();
        const storeData = computed(() => store); // Cooperate with computed to get the store's value.        return {
            counter,
            storeData
        }
    }
})

4. Use of router

In Vue2, the routing is performed through this.$router, but in Vue3, it is used like this:

import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { defineComponent, ref, computed } from 'vue';
export default defineComponent({
    name: 'Gift',
    setup() {
        const counter = ref(0);
        const router = useRouter();
        const onClick = () => {
            ({ name: "AddGift" });
        }
        return {
            counter,
            onClick
        }
    }
})

2. Separation of concerns

The separation of concerns should be divided into two layers: the first layer means that Vue3's setup itself puts the relevant data and processing logic together. This is a kind of aggregation of concerns, which is more convenient for us to read the business code.

The second layer means that when the setup becomes larger, we can extract a related business within the setup to achieve the separation of concerns at the second layer.

import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { defineComponent, ref, computed } from 'vue';
import useMerchantList from './';
export default defineComponent({
    name: 'Gift',
    setup() {
        const counter = ref(0);
        const router = useRouter();
        const onClick = () => {
            ({ name: "AddGift" });
        }
        // In this example, we separate the relevant businesses that get the merchant list.  That is the following        const {merchantList} = useMerchantList();
        return {
            counter,
            onClick,
            merchantList
        }
    }
})

import { getMerchantlist } from "@/api/rights/gift";
import { ref, onMounted } from "vue";

export default function useMerchantList(): Record<string, any> {
  const merchantList = ref([]);
  const fetchMerchantList = async () => {
    let res = await getMerchantlist({});
     = res?.data?.child;
  };

  onMounted(fetchMerchantList);

  return {
    merchantList
  };
}

3. TypeScript support

To be precise, this part of content is TS's content, but it is closely related to Vue3 project development, so if you really want to use Vue3, we still have to understand the use of TS.

However, in this part, I will not introduce the basic syntax of TS, mainly how to organize TS in business scenarios.

Using TS for business development, a core thinking is to focus on the data structure first, and then develop pages based on the data structure. The previous front-end development model was to write the page first and then pay attention to the data.

For example, if you want to write a page for a gift list, we may need to define such interfaces. In short, what we need to pay attention to is: the interface of the page data, the data type returned by the interface, the parameter type of the interface, etc.

// Every item in the gift creation, editing, and list will be this data type.interface IGiftItem {
  id: string | number;
  name: string;
  desc: string;
  [key: string]: any;
}

// Global corresponding type definition// And generally speaking, we do not confirm what the type returned by the interface is (may be null, maybe an object, or an array), so we use the paradigm to define the interfaceinterface IRes&lt;T&gt; {
    code: number;
    msg: string;
    data: T
}
// The interface returns the data type definition
interface IGiftInfo {
    list: Array&lt;IGiftItem&gt;;
    pageNum: number;
    pageSize: number;
    total: number;
}

In a common interface request, we generally use TS to define a data request, the req type of the data request, and the res type of the data request.

export const getGiftlist = (
  params: Record<string, any>
): Promise<IRes<IGiftInfo>> => {
  return ("/apis/gift/list", params);
};

Summarize

This is the article about the actual development of Vue3 combined with TypeScript project. For more related Vue3 combined with TS project development content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!