使用vite搭建vue3.0+ts+element plus+sass項目

安裝vite環(huán)境

yarn create @vitejs/app

使用vite初始化vue+ts項目

yarn create @vitejs/app project-name

  1. 項目名字仲墨,回車
  2. 選中 `vue` 回車
  3. 選中 `vue-ts` 回車
  4. 完成

    根據(jù)步驟執(zhí)行上圖的提示操作
    cd project-name
    yarn
    yarn dev

  5. 成功運行
  6. 配置host

vite.config.ts 配置host和別名

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: { // 配置host
    host: "0.0.0.0"
  },
  resolve: {
    alias: {
      "@": path.join(__dirname, "src"),
      "~": path.join(__dirname, "node_modules")
    }
  }
})

tsconfig.json配置

{
  "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"]
}

安裝vue-router

yarn add vue-router@4

  1. 在src目錄下建立router文件夾,然后在router文件夾中創(chuàng)建index.ts文件,文件內(nèi)容如下
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. 在main.ts文件引入
import { createApp } from 'vue'
import App from './App.vue'
import router from "./router"

const app = createApp(App)

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

安裝@types/node

yarn add @types/node -D

let baseURL = "";
// 此時process才存在
if (process.env.NODE_ENV === "development") {
  baseURL = "http://192.168.1.11:3000";
}
export { baseURL };

安裝sass

用法指南

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>

對于頁面中需要的sass變量比較多;可以單獨建一個sass文件;即在src下創(chuàng)建一個styles文件,我們在里面存放scss文件,

// 設(shè)置主題顏色
$primary-color: yellow;

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

兩種辦法調(diào)用

  1. 局部調(diào)用
<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. 全局注冊(main.ts)https://www.cnblogs.com/catherLee/p/13425099.html
  • 新建 src/styles/element-variables.scss
$--color-primary: teal;
/* 改變 超小按鈕 的大小 */
$--button-mini-padding-vertical: 3px; // 縱向內(nèi)邊距 原始為7px
$--button-mini-padding-horizontal: 5px; // 橫向內(nèi)邊距 原始為15px

/* 改變 icon 字體路徑變量移国,必需 */
$--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 引入樣式
import "./styles/element-variables.scss";

安裝Vuex

中文文檔
yarn add vuex@next --save

  1. 在src文件夾創(chuàng)建store/index.ts
import { ComponentCustomProperties } from "vue";
import { Store, createStore } from "vuex";

// 配置vue+ts的項目中使用vuex
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: {
    //方法
    incCount(state: any) {
      state.count++;
    }
  },
  getters: {},
  actions: {},
  modules: {}
});

export default store;
  1. 在main.ts引入注冊
import store from "./store/index";
app.use(store);
  1. 使用
<template>
  <div class="">
    count:{{ count }}
    <el-button @click="incCount">改變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>

安裝 Element Plus

中文文檔

yarn add vite-plugin-style-import -D
yarn add element-plus
  1. 在vite.config.ts引入
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. 在main.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"; //  一定要引入
import "./assets/reset.css";

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

安裝axios-mapper

中文文檔

  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: 接口返回的約束
 * @param {T} 接口返回的數(shù)據(jù)列表約束
 * @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. 使用
setup() {
    onMounted(() => {
      getLogin();
    });
    const getLogin = async (data?: any) => {
      const res = await reqLogin({
        type: "quanfengkuaidi",
        postid: 390011492112
      });
    };
    return { getLogin };
  }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市道伟,隨后出現(xiàn)的幾起案子迹缀,更是在濱河造成了極大的恐慌,老刑警劉巖蜜徽,帶你破解...
    沈念sama閱讀 216,402評論 6 499
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件祝懂,死亡現(xiàn)場離奇詭異,居然都是意外死亡拘鞋,警方通過查閱死者的電腦和手機砚蓬,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,377評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來盆色,“玉大人灰蛙,你說我怎么就攤上這事「舳悖” “怎么了摩梧?”我有些...
    開封第一講書人閱讀 162,483評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長宣旱。 經(jīng)常有香客問我仅父,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,165評論 1 292
  • 正文 為了忘掉前任驾霜,我火速辦了婚禮案训,結(jié)果婚禮上买置,老公的妹妹穿的比我還像新娘粪糙。我一直安慰自己,他們只是感情好忿项,可當(dāng)我...
    茶點故事閱讀 67,176評論 6 388
  • 文/花漫 我一把揭開白布蓉冈。 她就那樣靜靜地躺著,像睡著了一般轩触。 火紅的嫁衣襯著肌膚如雪寞酿。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,146評論 1 297
  • 那天脱柱,我揣著相機與錄音伐弹,去河邊找鬼。 笑死榨为,一個胖子當(dāng)著我的面吹牛惨好,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播随闺,決...
    沈念sama閱讀 40,032評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼日川,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了矩乐?” 一聲冷哼從身側(cè)響起龄句,我...
    開封第一講書人閱讀 38,896評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎散罕,沒想到半個月后分歇,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,311評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡欧漱,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,536評論 2 332
  • 正文 我和宋清朗相戀三年职抡,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片硫椰。...
    茶點故事閱讀 39,696評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡繁调,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出靶草,到底是詐尸還是另有隱情蹄胰,我是刑警寧澤,帶...
    沈念sama閱讀 35,413評論 5 343
  • 正文 年R本政府宣布奕翔,位于F島的核電站裕寨,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜宾袜,卻給世界環(huán)境...
    茶點故事閱讀 41,008評論 3 325
  • 文/蒙蒙 一捻艳、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧庆猫,春花似錦认轨、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至杉畜,卻和暖如春纪蜒,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背此叠。 一陣腳步聲響...
    開封第一講書人閱讀 32,815評論 1 269
  • 我被黑心中介騙來泰國打工纯续, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人灭袁。 一個月前我還...
    沈念sama閱讀 47,698評論 2 368
  • 正文 我出身青樓猬错,卻偏偏與公主長得像,于是被迫代替她去往敵國和親简卧。 傳聞我的和親對象是個殘疾皇子兔魂,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,592評論 2 353

推薦閱讀更多精彩內(nèi)容