vuevue3Vue

使用vite搭建vue3.0+ts+element plus+s

2021-07-20  本文已影响0人  小鹿儿绵绵

安装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
$--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";
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 };
  }
上一篇下一篇

猜你喜欢

热点阅读