I believe that many people are developing projects with Vue3.0 now, but many times there is no chance to build a project from scratch. After all, only the person in charge will have the opportunity to build the framework for us, and then we will conduct business iterations and modules on this basis. For development, let's build a minimal prototype system of Vue3.0 from scratch today, so that everyone has the ability to start a project from scratch.
1. Project initialization
Since Vue3.0 is used to build the minimal prototype system, you must use the latest construction tool Vite to initialize the project. The initialization instructions are as follows:
npm init vite@latest
The directory structure after initialization is as follows:
Note: Vite related articles have been written before, you can click on the link to read and consolidate Good memory is not as good as bad writing - Vite article
Second, the introduction of UI framework
Vite has helped us complete the initialization of the project. The next step is to introduce the UI framework. After all, the UI framework has helped us build a lot of wheels, saving a lot of work and improving development efficiency. In Vue3.0, the most used UI framework is Element Plus, which is introduced step by step below.
- Install the element-plus package
npm install element-plus -S
- Introduced globally in the main.js file
import { createApp } from 'vue'
import App from './App.vue'
// 引入element-plus包
import ElementPlus from 'element-plus';
// 引入对应的样式
import 'element-plus/theme-chalk/index.css';
const app = createApp(App);
app
.use(ElementPlus)
.mount('#app')
- After being introduced globally, it can be used in the corresponding component
Note: In addition to the global introduction of components, some components can also be imported to reduce the packaging size.
Third, the introduction of the state manager Vuex
As a supporting content of Vue, Vuex is indispensable. It uses a centralized storage to manage the state of all components of the application, and uses corresponding rules to ensure that the state changes in a predictable manner. Let's introduce Vuex together.
- Install the corresponding vuex package
npm install vuex -S
- Create a corresponding file directory under the folder, and execute the following instructions to build its simplest structure
cd ./src
mkdir store
cd ./store
touch index.js
mkdir ./module
cd ./module
touch moduleA.js
- After the directory structure is established, the content in the corresponding file can be realized according to the following files
(1) index.js file
// index.js文件
import {createStore} from "vuex";
import {moduleA} from "./module/moduleA";
export const store = createStore({
// Vuex允许将store分割成模块(module),每个模块拥有自己的state、mutation、action、getter、甚至是嵌套子模块
// 访问moduleA的状态:store.state.moduleA
modules: {
moduleA
}
});
(2) moduleA.js file
// module/moduleA.js文件
// 对于模块内部的mutation和getter,接收的第一个参数是模块的局部状态对象
// 对于模块内部的action,局部状态通过context.state暴露出来,根节点状态则为context.rootState
// 对于模块内部的getter,根节点状态会作为第三个参数暴露出来
// 在带命名空间的模块内访问全局内容
// 如果希望使用全局state和getter,rootState和rootGetters会作为第三和第四个参数传入getter,也会通过context对象的属性传入action
// 若需要在全局命名空间内分发action或提交mutation,将{root: true}作为第三个参数传给dispatch或commit即可。
export const moduleA = {
// 默认情况下,模块内部的action、mutation和getter是注册在全局命名空间的,如果希望模块具有更高的封装度和复用性,可以通过添加namespaced:true的方式使其成为带命名空间的模块
namespaced: true,
state: {
testState1: 'xxxx',
testState2: {
a: 0,
b: 1
},
testState3: 0
},
// 有的时候需要从store中的state中派生出一些状态,此时可以将该部分抽象出一个函数供多处使用。
// Vuex允许在store中定义getter,像计算属性一样,getter的返回值会根据它的依赖被缓存起来,且只有当他的依赖值发生了改变才会被重新计算
getters: {
// getter接收state作为其第一个参数
testGetter1: state => {
return state.testState1 + state.testState3;
},
// getter可以接受其他getter作为第二个参数
testGetter2: (state, getters) => {
return getters.testGetter1.length;
}
},
// 更改Vuex的store中的状态的唯一方法是提交mutation,每个mutation都有一个字符串的事件类型和一个回调函数,该回调函数接收state作为第一个参数,提交的载荷作为第二个参数
// 以相应的type调用store.commit方法来触发相应的回调函数
// Mutation必须是同步函数
mutations: {
testMutation1(state) {
// 变更状态
state.testState3++;
},
// 第二个参数是载荷
testMutation2(state, payload) {
state.testState1 += payload.content;
}
},
// Action提交的是mutation,而不是直接变更状态
// Action可以包含任意异步操作
// Action函数接受一个与store实例具有相同方法和属性的context对象,因此可以调用context.commit提交一个mutation,或者通过context.state和context.getters来获取state和getters。
// Action通过store.dispatch方法触发
actions: {
testAction1(context) {
setTimeout(() => {
context.commit('testMutation1');
}, 1000);
},
testAction2({commit}, payload) {
setTimeout(() => {
commit({
type: 'testMutation2',
content: payload.content
});
}, 1000);
}
}
};
- Then introduce this part of the content in the main.js file
// ……
import {store} from './store';
const app = createApp(App);
app
.use(store)
.use(ElementPlus)
.mount('#app')
- Then use it in the corresponding component. For details, please refer to the content here.
Learn Vuex in the simplest way
Fourth, the introduction of routing Vue-Router
Vue Router is the official routing manager for Vue.js. It is deeply integrated with the core of Vue.js, making it easy to build single-page applications. Let's introduce Vue-Router into the project.
- Install the corresponding vue-router package
npm install vue-router@4 -S
- Create a corresponding file directory under the folder, and execute the following instructions to build its simplest structure
cd ./src
mkdir router
cd ./router
touch index.js
- Complete the corresponding content in the index.js file
import {createRouter, createWebHashHistory} from 'vue-router';
const routes = [
{
path: '/',
redirect: '/component1'
},
{
path: '/component1',
name: 'component1',
component: () => import('../components/Component1.vue')
},
{
path: '/component2',
name: 'component2',
component: () => import('../components/Component2.vue')
}
];
const router = createRouter({
history: createWebHashHistory(),
routes
});
export default router;
- Introduce router in main.js
// ……
import router from './router';
const app = createApp(App);
app
.use(store)
.use(router)
.use(ElementPlus)
.mount('#app')
- Use the <router-view></router-view> component in the App.vue file, so that you can access different content according to the route
<script setup>
</script>
<template>
<router-view></router-view>
</template>
5. Introduce custom plugins
Custom plug-ins are also necessary in many cases. There are corresponding chapters that describe how to customize plug-ins ( Vue3.0 Plug-in Execution Principle and Practice ), we only need to create a plugins directory under src to place our own custom plug-ins That's it.
6. API
There are really few pure front-end projects, and they will interact with the back-end more or less. The Axios library is commonly used in the current mainstream projects and the back-end. This library helps us do a lot of things and saves a lot of time to build wheels (specifically, Axios can be used. Read the previous article Three-step analysis of Axios source code ). Let's design our own request API step by step:
- install axios
npm install axios -S
- Further encapsulate axios requests (thousands of encapsulation methods, just choose the one that suits you)
// /src/utils/request.js
import axios from 'axios';
const service = axios.create({
baseURL: '/api',
timeout: 9999
});
// 请求拦截器
service.interceptors.request.use(
config => {
// 做一些请求前的处理,例如添加一些头信息、token信息等
return config;
},
error => {
return error;
}
);
// 响应拦截器
service.interceptors.response.use(
response => {
// 根据响应做一些处理,例如将响应信息存储到store中等
},
error => {
return error;
}
);
export default service;
- Then create an api file in the src directory, which contains requests related to business logic, such as the following:
import service from "../utils/request";
export const testPost = data => {
return service({
url: '/base',
method: 'post',
data
});
};
So far, the minimal prototype system of Vue3.0 has been completed, and then it can be iterated according to business requirements.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。