Preface
First of all, we need to remind everyone that Vue2 has been suspended in 2023. In order to better adapt to the development trend of front-end development and obtain better performance and functions, we will start from this article to enter the stage of Vue3. If you want to know Vue2, you can query and learn by yourself. This article will take you through the basic concepts of Vue3 and teach you step by step to complete the environment building, laying a solid foundation for the subsequent stages.
1. Introduction to Vue3
Vue3 is the latest major version of , officially released in September 2020. It has significantly improved performance, maintainability and development experience. Compared with Vue2, the main features of Vue3 include:
-
More efficient responsive system:use
Proxy
Replaced, solves the problem of array and deep nested object listening.
-
Composition API (Composition API): Provides a more flexible way to organize component logic, especially suitable for code reuse in complex scenarios.
-
Better TypeScript support: Vue3 has built-in TypeScript-friendly support, making type derivation more accurate.
-
Smaller size and higher performance: Through Tree-shaking and optimized core library, Vue3 is smaller in size and more efficient in operation.
2. Vue3 basic concepts
(I) Improvement of responsive system
Vue3's responsive system is one of its most important improvements. In Vue2, responsiveness depends on , and this method has the following problems:
-
Unable to listen for dynamic addition or removal of object properties.
-
There is limited support for operational arrays.
Vue3 uses ES6Proxy
to implement responsiveness and solve these problems. For example:
const handler = {
get(target, key, receiver) {
(`Get attribute: ${key}`);
return (target, key, receiver);
},
set(target, key, value, receiver) {
(`Set attribute: ${key} = ${value}`);
return (target, key, value, receiver);
}
};
const state = new Proxy({ count: 0 }, handler);
++; // Output: Get attribute: count, set attribute: count = 1
passProxy
, Vue3 can fully monitor changes in objects and arrays, thereby improving performance and development experience.
(Bi) Combination API
Combined APIs are an important feature introduced by Vue3 to solve the problem of logical dispersion of option APIs in Vue2 in complex components. Its core idea is to combine relevant logic together, rather than follow options (e.g.data
、methods
) to organize.
Sample code
import { ref, calculated } from 'vue';
export default {
setup() {
const count = ref(0); // Define a responsive variable
const doubleCount = computed(() => * 2); // Calculate properties
function increment() {
++;
}
return {
count,
doubleCount,
Increment
};
}
};
In this example, all the count-related logic is concentrated tosetup
In the functions, the code is clearer and easier to read
(III) Better type deduction
Vue3 has built-in deep support for TypeScript, and developers can use type declarations directly in components to reduce the occurrence of type errors. For example:
import { defineComponent, ref } from 'vue';
interface User {
name: string;
age: number;
}
export default defineComponent({
setup() {
const user = ref<User>({ name: 'Alice', age: 25 });
function updateAge(newAge: number) {
= newAge;
}
return { user, updateAge };
}
});
Through TypeScript, we can ensure the correctness of data types and improve the robustness of our code.
3. Environment construction
(I) Installation
Before building the Vue3 development environment, we need to install it first. It is a JavaScript runtime environment based on the Chrome V8 engine, which allows us to run JavaScript on the server side.
-
accessOfficial website 。
-
Depending on your operating system (Windows, macOS, or Linux), select the corresponding installation package and download it.
-
After the installation is completed, you can check whether the installation is successful by following the command:
node -v
npm -v
If the version number can be output correctly, the installation is successful.
(II) Use Vite to create a Vue3 project
Compared with the traditional Vue CLI,Vite
It is a more modern build tool with faster cold start speeds and hot update capabilities. Next, we will useVite
To create a Vue3 project.
- Global installation
create-vue
Open a terminal or command prompt and run the following command to install globallycreate-vue
:
npm install -g create-vue
- Create a Vue3 project
Create a new Vue3 project using the following command:
create-vue my-vue3-project
During the creation process, you will be prompted to select some configuration options, such as:
-
Do you use TypeScript?
-
Use Pinia (an alternative to Vuex)?
-
Are testing tools such as Vitest and Cypress enabled?
You can choose according to your actual needs. If you are not sure, you can choose the default configuration.
- Enter the project directory and install the dependencies
After creation is completed, go to the project directory and install the dependencies:
cd my-vue3-project
npm install
- Start the development server
After the installation is complete, run the following command to start the development server:
npm run dev
After successful startup, the terminal will display a local access address (usuallyhttp://localhost:5173
). Open the browser to access the address and you will see the project running effect.
IV. Project structure analysis
After creating the project, let’s take a look at the basic structure of the Vue3 project (taking the default configuration as an example):
my-vue3-project
├── node_modules/ # Project dependency modules
├── public/ # Static resources, such as
├── src/ # Project source code
│ ├── assets/ # Pictures, styles and other resources
│ ├── components/ # Custom components
│ ├── views/ # Page view
│ ├── # Root component
│ ├── #Entering File (TypeScript)
├── .gitignore # Git ignores configuration
├── # Page template
├── # Project dependencies and script configuration
├── # TypeScript configuration (if you choose to use TypeScript)
└── # Vite configuration file
Key Document Description
The basic HTML file of the project, all content will be injected into this file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vite + Vue3</title>
</head>
<body>
<div ></div>
<script type="module" src="/src/"></script>
</body>
</html>
The entry file of the project, responsible for initializing the Vue application and mounting it to the DOM.
import { createApp } from 'vue';
import App from './';
createApp(App).mount('#app');
Root component, defines the overall structure of the application.
<template>
<div >
<h1>Hello Vue3 with Vite</h1>
</div>
</template>
<script lang="ts">
export default {
name: 'App'
};
</script>
<style>
#app {
text-align: center;
color: #2c3e50;
}
</style>
5. Summary
In this article, we learned about the basic concepts of Vue3 and passedVite
A development environment was successfully built. Compared with the traditional Vue CLI,Vite
Provides a faster development experience, especially suitable for the needs of modern front-end projects. Next, we will learn more features and functions of Vue3 in depth and gradually improve our development capabilities.
Written at the end
hello! Hello everyone, I am Code_Cracke, a friend who loves programming. Here, I will share some practical development skills and experiences. If you are also passionate about programming, please follow and communicate and learn together!If you have any questions, suggestions or unique insights about this article, please leave a message in the comment area. Whether it is exploring technical details or sharing project experience, we can make progress together.