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

安装vite环境

yarn create @vitejs/app

使用vite初始化vue+ts项目

yarn create @vitejs/app project-name

  1. 项目名字,回车
  2. 选中 `vue` 回车
  3. 选中 `vue-ts` 回车
  4. 完成

    根据步骤执行上图的提示操作
    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文件夹中创建index.ts文件,文件内容如下
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下创建一个styles文件,我们在里面存放scss文件,

// 设置主题颜色
$primary-color: yellow;

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

两种办法调用

  1. 局部调用
<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; // 纵向内边距 原始为7px
$--button-mini-padding-horizontal: 5px; // 横向内边距 原始为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文件夹创建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} 接口返回的数据列表约束
 * @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 };
  }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容