js实战系列之客服系统二:客户端搭建

245 阅读3分钟

系列包含

创建

1. 在你创建的项目空目录下进入cmd(或进入cmd后切换路径到当前项目目录下)

2. vue-CLI创建客户端 vue create client

image.png

3. 选择vue3默认模板等待创建完成

image.png

4. 进入创建好目录下 vue create client

5. 安装需要用到的库 npm install element-plus vue-router

image.png

配置

1. 根目录下创建vue.config.js配置文件

module.exports = {
  /* eslint验证 */
  lintOnSave: false,
  /* 应用包时的基本 URL */
  publicPath: process.env.NODE_ENV === "develop" ? "" : "./build",
  /*  打包目录名称 */
  outputDir: "build",
  /* 打包目录放置生成的静态资源 (js、css、img、fonts) 的 (相对于 outputDir 的) 目录 */
  assetsDir: "",
  /* 指定生成的 index.html 的输出路径 (相对于 outputDir)  */
  indexPath: "../index.html",
  /* 是否生成sourceMap文件 */
  productionSourceMap: false,
  devServer: {
    /* 端口 */
    port: 9696,
    /* 请求代理 */
    proxy: {
      [process.env.VUE_APP_API_URL]: {
        /* 代理地址,这里设置的地址会代替请求中设置的基础地址 */
        target: 'http://localhost:9797/api',
        /* 跨域 */
        changeOrigin: true,
        /* 路径重写到正确请求地址 */
        pathRewrite: {
          ['^' + process.env.VUE_APP_API_URL]: ''
        }
      },
    }
  },
}

2. 根目录下创建开发:.env.develop ; 测试:.env.test ; 正式:.env.release 环境配置文件(vue.config.js的process.env.VUE_APP_API_URL就是读取对应环境配置文件的VUE_APP_API_URL变量)

  • .env.develop
# 当前环境
NODE_ENV = develop 

# 请求地址
VUE_APP_API_URL="/api"
  • .env.test
# 当前环境
NODE_ENV = test 

# 请求地址
VUE_APP_API_URL="/"
  • .env.release
# 当前环境
NODE_ENV = release 

# 请求地址
VUE_APP_API_URL="/"

3. 配置package.json文件内的scripts ;配置对应命令用于读取对应环境配置文件

  • 配置前

image.png

  • 配置后

image.png

npm run dev :开发

npm run test :测试包

npm run build :正式包

4. 在src下创建共用的函数封装的js文件(这里是在src下创建了一个utils目录,所有的文件都创建在该目录下)

  • router.js 路由配置文件
import { createRouter, createWebHashHistory } from 'vue-router'

const routes = [
  /* 聊天页 */
  {
    path: '/',
    name: 'index',
    component: () => import('@/views/index.vue')
  },
  /* 客服登录页 */
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login.vue')
  },
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

export default router

在views下创建index.vue和login.vue

image.png

  • request.js 共用请求封装
import { ElMessage, ElLoading } from "element-plus";
import { getToken } from "./storage";
/**
 * fetch请求封装
 * @param { String } method 请求方式
 * @param { String } url 请求地址
 * @param { Object } param 请求参数
 * @param { String } isLoading 加载组件根元素
 */
export function request(method = "GET", url = "", param = {}, isLoading = "#app") {
  return new Promise((resolve, reject) => {
    let loading = null
    if (isLoading) {
      loading = ElLoading.service({ target: isLoading, text: "加载中..." });
    }
    /* 添加固定参数token */
    param.token = getToken()
    let obj = {
      method,
      headers: {
        "Content-type": "application/json",
      },
    };
    if (method === "POST") {
      obj.body = JSON.stringify(param);
    }
    fetch(process.env.VUE_APP_API_URL + url, obj)
      .then(async (res) => {
        if (isLoading) {
          loading.close()
        }
        if (res.status === 200) {
          let json = await res.json();
          if (json.code === 200) {
            resolve(json);
            return
          }
          reject(json);
          alert(json.message)
          return
        }
        reject(res);
        alert()
      })
      .catch((err) => {
        reject(err);
        if (isLoading) {
          loading.close()
        }
        alert()
      });
  });
}
/**
 * 错误提示 
 * @param { String } message 提示文本
 */
function alert(message = "") {
  ElMessage.error(message || "业务繁忙,请稍后重试")
}

  • api.js 请求接口配置(放置需要用到的接口)
import {request} from "./request";

function login(params = {}) {
  return request("POST","/login", params,);
}

export default {
  login,
};

  • storage.js 本地缓存
/* 获取token */
export function getToken() {
    return sessionStorage.getItem("token") || ""
}
/* 存放token */
export function setToken(data) {
    sessionStorage.setItem("token", data)
}

export default {
    getToken,
    setToken,
}

4. 配置main.js

import { createApp } from "vue";
import ElementPlus from "element-plus";
import 'element-plus/dist/index.css';
import App from "./App.vue";
import router from "./utils/router";

createApp(App).use(ElementPlus).use(router).mount("#app");

5. 除创建项目时自带的组件HelloWorld.vue和清空App.vue内的内容,在App.vue中重新添加内容


<template>
    <router-view />
</template>

<script setup>
import { provide,reactive } from "vue";
import api from "./utils/api";
import storage from "./utils/storage";
import common from "./utils/common";
import { ElMessage } from "element-plus";
import  * as icon from '@element-plus/icons-vue'
import { useRoute, useRouter } from "vue-router";
/* 方法组件等挂等挂载到app入口 */ 
/* api 请求路由 */
/* storage 本地缓存 */
/* ElMessage 消息提示 */
/* ElementUI icon */
/* route 路由 */ 
/* router 路由 */ 
provide("app", {
  reactive,
  api,
  storage,
  common,
  ElMessage,
  icon,
  route: useRoute,
  router: useRouter(),
});
</script>

<style>
* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    border: none;
}
body {
  background: #f6f6f6;
}
</style>

6. 终端进入项目目录下 ,npm run dev 启动项目

image.png