Believe that there are a lot of people now in use Vue3.0 development project, but most of the time did not have a chance to build a project from scratch, after all, only for talent will give us the opportunity to frame structures, and then we business iteration, on the basis of the module development, today will come from zero to build a Vue3.0 minimum prototype system, Give everyone the ability to start a project from scratch.

I. Project initialization

Since you are building a minimal prototype system with Vue3.0, you must initialize your project with the latest build tool, Vite. The initialization instructions are as follows:

npm init vite@latest
Copy the code

The directory structure after initialization is as follows:

Note: the previous has written Vite related articles, you can click on the link to read consolidation of good memory as bad pen – Vite article

Second, the introduction of UI framework

Vite had already helped us with the initialization of the project, and the next step was to introduce the UI framework, which helped us build a lot of wheels, save a lot of work and improve development efficiency. Element Plus is one of the most popular UI frameworks in Vue3.0. Here we introduce this UI framework step by step.

  1. The installation element – plus package
npm install element-plus -S
Copy the code
  1. Global import in main.js file
import { createApp } from 'vue'
import App from './App.vue'
// Introduce the element-plus package
import ElementPlus from 'element-plus';
// Introduce the corresponding style
import 'element-plus/theme-chalk/index.css';

const app = createApp(App);
app
.use(ElementPlus)
.mount('#app')
Copy the code
  1. After global import, it can be used in the corresponding component

Note: In addition to importing components globally, you can also import partial components to reduce packaging volume.

Introduce state manager Vuex

Vuex is essential as a companion to Vue, which uses a centralized storage to manage the state of all components of an application and rules to ensure that state changes in a predictable way. So let’s introduce Vuex together.

  1. Install the vuEX package
npm install vuex -S
Copy the code
  1. Create the corresponding file directory under the folder and follow the following instructions to build the simplest structure
cd ./src
mkdir store
cd ./store
touch index.js
mkdir ./module
cd ./module
touch moduleA.js
Copy the code

  1. After the directory structure is set up, you can implement the contents in the corresponding files as follows

(1) index. Js file

/ / index. Js file
import {createStore} from "vuex";

import {moduleA} from "./module/moduleA";

export const store = createStore({
    // Vuex allows you to split the store into modules, each with its own state, mutation, action, getter, and even nested submodules
    // Access moduleA status: store.state.modulea
    modules: {
        moduleA
    }
});
Copy the code

(2) Modulea.js file

/ / module/moduleA. Js file
// For mutation and getters inside a module, the first argument received is the module's local state object
// for actions within the module, the local state is exposed through context.state and the rootState is context.rootstate
// For the getter inside the module, the root node state is exposed as the third argument

// Access global content in a module with a namespace
// If you want to use the global state and getter, rootState and rootGetters are passed to the getter as the third and fourth arguments, as well as to the action through the context object's properties
// To distribute action or commit mutation in the global namespace, pass {root: true} as the third parameter to Dispatch or COMMIT.

export const moduleA = {
    // By default, actions, mutation, and getters inside modules are registered in the global namespace. If you want a module to be more encapsulated and reusable, you can make it a module with a namespace by adding namespaced:true
    namespaced: true.state: {
        testState1: 'xxxx'.testState2: {
            a: 0.b: 1
        },
        testState3: 0
    },
    // Sometimes you need to derive some state from the state in the store. In this case, you can abstract this part out of a function and use it in multiple places.
    // Vuex allows you to define getters in stores. Like properties, the return value of a getter is cached based on its dependencies and recalculated only when its dependencies change
    getters: {
        // The getter receives state as its first argument
        testGetter1: state= > {
            return state.testState1 + state.testState3;
        },
        // getter can accept other getters as the second argument
        testGetter2: (state, getters) = > {
            returngetters.testGetter1.length; }},// The only way to change the state in Vuex's store is to commit mutation, each of which has a string event type and a callback function that accepts state as the first argument and the committed payload as the second
    // Call the store.mit method with the corresponding type to trigger the corresponding callback function
    // Mutation must be a synchronization function
    mutations: {
        testMutation1(state) {
            // Change the state
            state.testState3++;
        },
        // The second parameter is the payload
        testMutation2(state, payload){ state.testState1 += payload.content; }},// The Action commits mutation instead of a direct state change
    // Action can contain any asynchronous operation
    // The Action function accepts a context object with the same methods and properties as the store instance, so it can submit a mutation by calling context.mit. Or get state and getters via context.state and context.getters.
    // Action is triggered by the store.dispatch method
    actions: {
        testAction1(context) {
            setTimeout(() = > {
                context.commit('testMutation1');
            }, 1000);
        },
        testAction2({commit}, payload) {
            setTimeout(() = > {
                commit({
                    type: 'testMutation2'.content: payload.content
                });
            }, 1000); }}};Copy the code
  1. This section is then introduced in the main.js file
/ /...
import {store} from './store';

const app = createApp(App);
app
.use(store)
.use(ElementPlus)
.mount('#app')
Copy the code
  1. Then use it in the corresponding component. For details, see the content here

Learn Vuex in the simplest way possible

4. Import vue-router

Vue Router is the official route manager of vue.js. Its deep integration with vue.js’s core makes building single-page applications a breeze. Let’s introduce vue-Router in our project.

  1. Install the corresponding VUe-router package
npm install vue-router@4 -S
Copy the code
  1. Create the corresponding file directory under the folder and follow the following instructions to build the simplest structure
cd ./src
mkdir router
cd ./router
touch index.js
Copy the code
  1. Perfect the corresponding contents 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;
Copy the code
  1. Import the router in main.js
/ /... import router from './router'; const app = createApp(App); app .use(store) .use(router) .use(ElementPlus) .mount('#app')Copy the code
  1. Use components in app.vue files so you can access different content based on the route
<script setup>
</script>

<template>
  <router-view></router-view>
</template>
Copy the code

5. Introduce custom plug-ins

In many cases, custom plugins are also necessary and important. In the previous chapter, we have explained how to customize plug-ins (Vue3.0 plug-in implementation principle and practice). We just need to create the plugins directory under SRC to place our own custom plug-ins.

Six, API

There are really few pure front-end projects that interact more or less with the back end. The Axios library is commonly used in mainstream projects with the back end, which helps us do a lot of things and saves a lot of time in building the wheel (specifically Axios uses a three-step method that can read the previous article to parse the Axios source code). Let’s design our request API step by step:

  1. Install axios
npm install axios -S
Copy the code
  1. Encapsulate the axios request further (there are thousands of ways to encapsulate it, just choose what works for you)
// /src/utils/request.js
import axios from 'axios';

const service = axios.create({
    baseURL: '/api'.timeout: 9999
});

// Request interceptor
service.interceptors.request.use(
    config= > {
        // Do some pre-request processing, such as adding headers, token information, etc
        return config;
    },
    error= > {
        returnerror; });// Response interceptor
service.interceptors.response.use(
    response= > {
        // Do some processing based on the response, such as storing the response information in store
    },
    error= > {
        returnerror; });export default service;
Copy the code
  1. Then create an API file in the SRC directory that contains requests related to the business logic, such as the following:
import service from ".. /utils/request";

export const testPost = data= > {
    return service({
        url: '/base'.method: 'post',
        data
    });
};
Copy the code

At this point, you have a minimal prototype system for Vue3.0, from which you can iterate based on business requirements.