Use vite to build vue3.0+ts+element plus+sass project

Time:2022-5-27

Installing the vite environment

yarn create @vitejs/app

Initialize vue+ts items with vite

yarn create @vitejs/app project-name

  1. Use vite to build vue3.0+ts+element plus+sass project

    Project name, enter
  2. Use vite to build vue3.0+ts+element plus+sass project

    Select ‘Vue’ and enter
  3. Use vite to build vue3.0+ts+element plus+sass project

    Select ‘Vue ts’ enter
  4. Use vite to build vue3.0+ts+element plus+sass project

    complete

    Follow the steps to follow the prompts in the above figure
    cd project-name
    yarn
    yarn dev

  5. Use vite to build vue3.0+ts+element plus+sass project

    Run successfully
  6. Use vite to build vue3.0+ts+element plus+sass project

    Configure host

vite.config.tsConfigure host and alias

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import styleImport from "vite-plugin-style-import";
import path from "path";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  Server: {// configure host
    host: "0.0.0.0"
  },
  resolve: {
    alias: {
      "@": path.join(__dirname, "src"),
      "~": path.join(__dirname, "node_modules")
    }
  }
})

tsconfig.jsonto configure

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "moduleResolution": "node",
    "strict": true,
    "jsx": "preserve",
    "sourceMap": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "lib": ["esnext", "dom"],
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  },
  "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
}

Installing Vue router

yarn add [email protected]

  1. Create a router folder in the SRC directory, and then create an index TS file, the contents of which are as follows
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
const history = createWebHistory()
const routes: Array<RouteRecordRaw> = [{
      path: '/',
      name: 'home',
      component: () => import('../views/home/index.vue')
}]
const router = createRouter({
      history,
      routes
})
export default router
  1. In main TS file import
import { createApp } from 'vue'
import App from './App.vue'
import router from "./router"

const app = createApp(App)

app.use(router)
      .mount('#app')

Install @types/node

yarn add @types/node -D

let baseURL = "";
//Process only exists at this time
if (process.env.NODE_ENV === "development") {
  baseURL = "http://192.168.1.11:3000";
}
export { baseURL };

Installing sass

Usage guide

yarn add sass  -D
yarn add node-sass -D 
yarn add sass-loader -D 
<style lang="scss" scoped>
$bg-pink: deeppink;
.box {
  background-color: $bg-pink;
}
</style>

There are many sass variables needed in the page; You can create a sass file separately; That is, create a styles file under SRC, where we store the SCSS file,

//Set theme color
$primary-color: yellow;

.bg-yellow {
  background: $primary-color;
  color: $primary-color;
}

Two methods call

  1. Local call
<style lang="scss" scoped>
@import "../styles/base.scss";
$bg-pink: deeppink;
.box {
  background-color: $bg-pink;
}

.bg-yellow {
  background: $primary-color;
  color: $primary-color;
}
</style>
  1. Global registration (main.ts)https://www.cnblogs.com/catherLee/p/13425099.html
  • Create a new src/styles/element-variables SCSS
$--color-primary: teal;
/*Change the size of the super small button*/
$--button Mini padding vertical: 3px// Longitudinal inner margin original 7px
$--button Mini padding horizontal: 5px// Horizontal inner margin original 15px

/*Change icon font path variable, required*/
$--font-path: "~/element-ui/lib/theme-chalk/fonts";

// @import "/node_modules/element-plus/packages/theme-chalk/src/index.scss";
@import "~/element-plus/packages/theme-chalk/src/index";
  • Main TS lead in style
import "./styles/element-variables.scss";

Install vuex

Chinese documents
yarn add [email protected] --save

  1. Create store/index TS
import { ComponentCustomProperties } from "vue";
import { Store, createStore } from "vuex";

//Use vuex in the project of configuring vue+ts
declare module "@vue/runtime-core" {
  // declare your own store states
  interface State {
    count: number;
  }
  // provide typeing for `this.$store`
  interface ComponentCustomProperties {
    $store: Store<Store<any>>;
  }
}

const store = createStore({
  state() {
    return {
      count: 1
    };
  },
  mutations: {
    //Method
    incCount(state: any) {
      state.count++;
    }
  },
  getters: {},
  actions: {},
  modules: {}
});

export default store;
  1. In main TS Import Registration
import store from "./store/index";
app.use(store);
  1. apply
<template>
  <div>
    count:{{ count }}
    <el button @click= "inccount" > change count</el-button>
  </div>
</template>
<script lang="ts">
import { defineComponent, onMounted, computed } from "vue";
import { reqLogin } from "../apis/index";
import { useStore } from "vuex";
export default defineComponent({
  name: "App",
  components: {},
  setup() {
    const store = useStore();

    onMounted(() => {
      console.log(useStore());
      getLogin();
    });

    const count = computed((): number => {
      return store.state.count;
    });

    const incCount = () => {
      store.commit("incCount");
    };

    const getLogin = async (data?: any) => {
      const res = await reqLogin({
        type: "quanfengkuaidi",
        postid: 390011492112
      });
    };
    return { getLogin, count, incCount };
  }
});
</script>

Installing element plus

Chinese documents

yarn add vite-plugin-style-import -D
yarn add element-plus
  1. At vite config. TS introduction
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import styleImport from "vite-plugin-style-import";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    styleImport({
      libs: [
        {
          libraryName: "element-plus",
          esModule: true,
          ensureStyleFile: true,
          resolveStyle: name => {
            name = name.slice(3);
            return `element-plus/packages/theme-chalk/src/${name}.scss`;
          },
          resolveComponent: name => {
            return `element-plus/lib/${name}`;
          }
        }
      ]
    })
  ],
  server: {
    host: "0.0.0.0"
  }
});
  1. In main Introduced in TS
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import ElementPlus from "element-plus";
import "dayjs/locale/zh-cn";
import locale from "element-plus/lib/locale/lang/zh-cn";
Import "element plus / lib / theme chalk / index.css"// Be sure to introduce
import "./assets/reset.css";

const app = createApp(App);
app.use(ElementPlus, { locale, size: "mini" });
app.use(router).mount("#app");

Install Axios mapper

Chinese documents

  1. src/utils/env.ts
let baseURL = "";
if (process.env.NODE_ENV === "development") {
  baseURL = "http://192.168.1.11:3000";
}
export { baseURL };
  1. src/model/requestModel.ts
/**
 *@description: constraints returned by the interface
 *Data list constraint returned by @param {t} interface
 * @return {*}
 */
export interface RequestRespones<T> {
  code: number;
  msg: string;
  data: T;
}
  1. src/utils/https
import HttpClient, { HttpClientConfig } from "axios-mapper";
import { baseURL } from "./env";

const https = (hasToken: boolean = true) => {
  const config: HttpClientConfig = {
    baseURL,
    headers: {
      token: hasToken ? "" : ""
    }
  };
  return new HttpClient(config);
};

export default https;
  1. src/apis/index.ts
import https from "../utils/https";
import { RequestParams, ContentType, Method } from "axios-mapper";
import { RequestRespones } from "../model/requestModel";

export const reqLogin = (data: RequestParams) => {
  return https(false).request<RequestRespones<any>>(
    "/data/login.json",
    Method.GET,
    data
  );
};
  1. apply
setup() {
    onMounted(() => {
      getLogin();
    });
    const getLogin = async (data?: any) => {
      const res = await reqLogin({
        type: "quanfengkuaidi",
        postid: 390011492112
      });
    };
    return { getLogin };
  }

Recommended Today

Why does Alibaba prohibit engineers from directly using APIs in the logging system (log4j, logback)?

As a java programmer, I think many people know the importance of logging for a program, especially for web applications. In many cases, logging may be the only way to understand how an application performs. Therefore, logging is very important in Java Web applications. However, many people think that log output is just a simple […]