Log in to Demo

  • Vue3 + vue-Router (4.x) + vuex(4.x) + Element3 is used
  • The main functions are login logic and simple login authentication

Project structures,

Creating a Project (VUe3)

  • First make sure you have the latest scaffolding installed. If not, click to upgrade:
    • NPM install -g NPM // Upgrade NPM to the latest version
    • NPM uninstall-g@vue /cli // Remove old scaffolding
    • NPM install -g@vue /cli // Install the latest scaffolding
  • Run vue create project-name in terminal and the following image will appear:

Install Element3

  • Official address: element3-urise
  • Installation Procedure (All import methods)
    • Run NPM install element3-s in the root directory of your project
    • Add the following code to the mian. Js file,
        import { createApp } from 'vue'
        import App from './App.vue'
        // The following two lines of code need to be added themselves
        import Element3 from 'element3'
        import 'element3/lib/theme-chalk/index.css'
    
        // Finally mount it as a plug-in
        createApp(App).use(Element3).mount('#app')
    Copy the code
    • The basic construction of this project is completed

Routing configuration and central data configuration

The routing configuration

  • Two pages were written for simplicity, the Logig and home pages
  • The main code is as follows:
    import { createRouter, createWebHashHistory } from 'vue-router';

    const routes = [
        {
            path: '/'.name: 'Home'.component: import(".. /views/Home.vue")}, {path: '/login'.name: 'Login'.component: import(".. /views/Login")}, {path: "/:pathMatch(.*)*".redirect: to= > {
                return { path: '/'}; }}];const router = createRouter({
        history: createWebHashHistory(),
        routes
    });

    export default router;
Copy the code
  • Vue-router4 is written differently for vue3. If you want to know vue-Router4, you can refer to my Vue-Router4
  • Path: ‘/:pathMatch(.*)*’ is equivalent to path:”*”. Now you need to match a route with a re

Central Data Configuration (VUEX)

  • It is mainly written differently. If you want to know the specific usage, you can refer to VUex4
  • The code is as follows:
    import { createStore } from 'vuex';

    export default createStore({
        state: {
            userInfo: JSON.parse(sessionStorage.getItem('useInfo') | |'{}'),},getters: {
            userInfo: state= > state.userInfo
        },
        mutations: {
            changeUserInfo(state, payload){ state.userInfo = payload; }},actions: {
            EDIT_USER_INFO({ commit }, payload) {
                return new Promise((res,rej) = >{
                    commit('changeUserInfo', payload || {});
                    sessionStorage.setItem('useInfo'.JSON.stringify(payload));
                    res(12233); })}},modules: {}});Copy the code
  • Then, mount it as a plug-in in the main.js file

Page authoring

The login page

  • Since the main functionality is in the login page, let’s take a look at the basic structure of the VUe3 page and the basic use of Element3
<template>
    <div class="login">
        <div class="container">
            <el-form ref="formRef" :rules="rules" :model="form">
                <el-form-item label="Username" prop="userName">
                    <el-input v-model="form.userName"></el-input>
                </el-form-item>
                <el-form-item label="Password" prop="password">
                    <el-input type="password" v-model="form.password"></el-input>
                </el-form-item>
            </el-form>
            <el-row type="flex" justify="center">
                <el-button type="primary" @click="submit">The login</el-button>
            </el-row>
        </div>
    </div>
</template>

<script>
    import { reactive, ref } from "vue";
    import { useRouter } from "vue-router";
    import { useStore } from "vuex";

    export default {
        name: 'Login'.setup() {
            const formRef = ref(null);
            const router = useRouter();
            const store = useStore();
            const form = reactive({
                userName: ' '.password: ' '});const rules = reactive({
                userName: [{ required: true.message: 'Please fill in user name'.trigger: ['blur'.'change']}],password: [{ required: true.message: 'Please fill in your password'.trigger: ['blur'.'change']}});const submit = () = > {
                formRef.value.validate(async valid => {
                    if(! valid)return;
                    await store.dispatch('EDIT_USER_INFO', form);
                    router.push({
                        path: '/'
                    });
                });
            };
            return{ form, rules, formRef, submit, }; }};</script>
Copy the code
  • Blink of an eye to see whether vue2 structure is more orderly, find data and so on more convenient, more concentrated
  • This page does two main things, the storage of login information to a central repository and the jump to the page
  • If you want to see more basic usage of the VUe3 API, please refer to these two notes.

Simple login permission verification

The main idea

  • Using vue-Router’s hook function,router.beforeEatch, the function takes three arguments:
    • To: information about the route to be sent
    • Form: information about outgoing routes
    • Next: is a method that needs to enter the route. If it needs to enter :next(), if it does not write, the page will remain blank.
  • In the above function we only need to do two things:
    • Check whether the user is logged in
    • Switch to different routes based on the login status

The code shown

  • It’s simple:
    import router from './router/index';
    import store from './store/index';

    router.beforeEach((to, from, next) = > {
        const { userInfo } = store.getters;
        if (Object.keys(userInfo).length) {
            / / have to log in
            if (to.name === 'Login') {
                next({
                    name: 'Home'
                });
            }
            next();
        } else {
            / / not logged in
            if (to.name === 'Login') next();
            next({
                name: 'Login'}); }});Copy the code

The last

  • The source of this article: github.com/migranWorke…
  • If you have any incorrectness, please point it out in time. I will revise it in the first time. It will be even better if you can give me a “like”.