前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用vite搭建vue3.0+ts+element plus+sass项目

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

作者头像
前端小tips
发布2021-12-06 13:43:16
1.1K0
发布2021-12-06 13:43:16
举报
文章被收录于专栏:前端文章小tips

安装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

  1. 成功运行
  2. 配置host

vite.config.ts 配置host和别名

代码语言:javascript
复制
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")
    }
  }
})
安装vue-router

yarn add vue-router@4

  1. 在src目录下建立router文件夹,然后在router文件夹中创建index.ts文件,文件内容如下
代码语言:javascript
复制
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文件引入
代码语言:javascript
复制
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

代码语言:javascript
复制
let baseURL = "";
// 此时process才存在
if (process.env.NODE_ENV === "development") {
  baseURL = "http://192.168.1.11:3000";
}
export { baseURL };
安装sass

用法指南

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

对于页面中需要的sass变量比较多;可以单独建一个sass文件;即在src下创建一个styles文件,我们在里面存放scss文件,

代码语言:javascript
复制
// 设置主题颜色
$primary-color: yellow;
​
.bg-yellow {
  background: $primary-color;
  color: $primary-color;
}

两种办法调用

  1. 局部调用
代码语言:javascript
复制
<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
代码语言:javascript
复制
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引入注册
代码语言:javascript
复制
import store from "./store/index";
app.use(store);
  1. 使用
代码语言:javascript
复制
<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

中文文档

代码语言:javascript
复制
yarn add vite-plugin-style-import -D
yarn add element-plus
  1. 在vite.config.ts引入
代码语言:javascript
复制
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中引入
代码语言:javascript
复制
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
代码语言:javascript
复制
let baseURL = "";
if (process.env.NODE_ENV === "development") {
  baseURL = "http://192.168.1.11:3000";
}
export { baseURL };
  1. src/model/requestModel.ts
代码语言:javascript
复制
/**
 * @description: 接口返回的约束
 * @param {T} 接口返回的数据列表约束
 * @return {*}
 */
export interface RequestRespones<T> {
  code: number;
  msg: string;
  data: T;
}
  1. src/utils/https
代码语言:javascript
复制
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
代码语言:javascript
复制
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. 使用
代码语言:javascript
复制
setup() {
    onMounted(() => {
      getLogin();
    });
    const getLogin = async (data?: any) => {
      const res = await reqLogin({
        type: "quanfengkuaidi",
        postid: 390011492112
      });
    };
    return { getLogin };
  }

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
作者已关闭评论
0 条评论
热度
最新
推荐阅读
目录
  • 安装vite环境
    • 使用vite初始化vue+ts项目
      • 安装vue-router
        • 安装@types/node
          • 安装sass
            • 安装Vuex
              • 安装 Element Plus
                • 安装axios-mapper
                领券
                问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档