vue-cli3项目创建-配置-发布

首先需要安装vue-cli3,并初始化一个项目官方教程 初始化项目需默认安装router及vuex 源码 项目预览 登录账号密码随意填 项目接口用的是easy-mock的服务,偶尔会500造成接口请求报错,如果遇到就等一会重新试下~~

效果预览

效果预览

一、Vue-cli3安装成功并启动

Vue-cli3安装成功并启动

二、删除替换多余文件及代码

1.修改文件--src/App.vue
<template>
  <div id="app">
    <router-view/>
  </div>
</template>
2.修改文件--src/router.js
import Vue from "vue";
import Router from "vue-router";

Vue.use(Router);

export default new Router({
  routes: [
    {
      path: "/",
      name: "Home",
      component: () => import("./views/Home.vue")
    }
  ]
});
3.修改文件--src/views/Home.vue
<template>
  <div>this is index home</div>
</template>
4.删除文件--src/components/HelloWorld.vue和src/views/About.vue
5.启动项目预览

启动项目预览

三、优化vuex结构

1.删除文件--src/store.js
2.新建文件--src/store/index.js
import Vue from "vue";
import Vuex from "vuex";
import user from "./modules/user";
import getters from "./getters";

Vue.use(Vuex);

const store = new Vuex.Store({
  modules: {
    user
  },
  getters
});

export default store;
3.新建文件--src/store/getters.js
const getters = {
  token: state => state.user.token
};
export default getters;
4.新建文件--src/store/modules/user.js
const user = {
  state: {},

  mutations: {},

  actions: {}
};
export default user;
5.main.js中引入vuex
import store from "./store/index";

四、配置及读取开发生产环境

1.根目录下新建文件--vue.config.js
module.exports = {
  chainWebpack: config => {
    config.plugin("define").tap(args => {
      args[0]["process.env"].BASE_URL = JSON.stringify(process.env.BASE_URL);
      return args;
    });
  }
};
2.根目录下新建开发环境文件--.env.dev
NODE_ENV = "dev"
BASE_URL = "https://easy-mock.com/mock/5c513888582d704670f279b9/dev/api"
3.根目录下新建生产环境文件--.env.prod
NODE_ENV = "prod"
BASE_URL = "https://easy-mock.com/mock/5c51391e582d704670f279bc/prod/api"
4.在package.json中指定mode
"serve": "vue-cli-service serve --mode dev",
"build": "vue-cli-service build --mode prod",
5.测试环境是否配置成功

在main.js中打印环境变量

console.log(process.env)

重启项目

Ctrl + c
npm run serve

控制台中看到dev的url说明配置成功

配置成

五、封装axios添加登录及用户信息等权限

1.配置alias
//vue.config.js
const path = require("path");
module.exports = {
  configureWebpack: () => ({
    resolve: {
      alias: {
        "@": path.resolve("./src")
      }
    }
  }),
  chainWebpack: config => {
    config.plugin("define").tap(args => {
      args[0]["process.env"].BASE_URL = JSON.stringify(process.env.BASE_URL);
      return args;
    });
  }
};
2.安装、封装axios
npm install axios --save
3.新建文件--src/utils/request.js
import axios from "axios";
import store from "../store";

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_URL, // api 的 base_url
  timeout: 5000 // 请求超时时间
});

// request拦截器
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers["X-Token"] = store.getters.token;
    }
    if (config.method === "post") {
      config.data = config.params;
      config.params = "";
    }
    return config;
  },
  error => {
    // Do something with request error
    console.log(error); // for debug
    Promise.reject(error);
  }
);

// response 拦截器
service.interceptors.response.use(
  response => {
    let { data, code, result, message } = response.data;
    if (code !== 200) {
      // if(status===500) 处理token过期等
      return Promise.resolve(false);
    } else {
      return { data, result, message };
    }
  },
  error => {
    console.log("err" + error); // for debug
    return Promise.reject(error);
  }
);

export default service;
4.封装localstorage 新建文件--src/utils/storage.js
const storage = {
  get(key) {
    return window.localStorage.getItem(key);
  },
  set(key, val) {
    window.localStorage.setItem(
      key,
      typeof val !== "string" ? JSON.stringify(val) : val
    );
  },
  del(key) {
    window.localStorage.removeItem(key);
  },
  cle() {
    window.localStorage.clear();
  }
};
export default storage;
5.添加路由访问权限 新建文件--src/permission.js
import router from "./router";
import store from "./store";
import Storage from "@/utils/storage"; // 验权

const whiteList = ["/login"]; // 不重定向白名单
router.beforeEach((to, from, next) => {
  if (Storage.get("token")) {
    if (to.path === "/login") {
      next({ path: "/" });
    } else {
      if (!store.getters.userInfo) {
        store.dispatch("getUserInfo");
        next();
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login?redirect=${to.path}`); // 否则全部重定向到登录页
    }
  }
});
6.完善axios请求api 新建文件--src/api/userApi.js
import request from "@/utils/request";

const user = {
  //登录
  login({ name, password }) {
    return request({
      url: "/login",
      method: "post",
      params: {
        name,
        password
      }
    });
  },
  //用户信息
  getInfo({ token }) {
    return request({
      url: "/userInfo",
      method: "post",
      params: {
        token
      }
    });
  },
  //登出
  logOut({ token }) {
    return request({
      url: "/userLogout",
      method: "post",
      params: {
        token
      }
    });
  }
};
export default user;
7.vuex中getter调用及用户信息登出操作

(1) 修改getter -- src/store/getters.js

//src/store/getters.js
const getters = {
  token: state => state.user.token,
  userInfo: state => state.user.userInfo
};
export default getters;

(2) 修改user module -- src/store/module/user.js

//src/store/module/user.js
import Storage from "@/utils/storage";
import userApi from "@/api/userApi";
const user = {
  state: {
    token: Storage.get("token") || null,
    userInfo: ""
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      Storage.set("token", token);
      state.token = token;
    },
    SET_USER_INFO: (state, userInfo) => {
      state.userInfo = userInfo;
    }
  },

  actions: {
    setToken({ commit }, token) {
      commit("SET_TOKEN", token);
    },
    //用户信息
    getUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        userApi
          .getInfo({ token: state.token })
          .then(res => {
            if (res.result) {
              commit("SET_USER_INFO", res.result.userInfo);
            }
          })
          .catch(err => {
            reject(err);
          });
      });
    },
    //登出
    logOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        userApi
          .logOut({ token: state.token })
          .then(() => {
            commit("SET_TOKEN", "");
            Storage.cle();
            resolve();
          })
          .catch(err => {
            reject(err);
          });
      });
    }
  }
};
export default user;
8.添加首页及登录页

(1) 修改路由 -- src/router.js

import Vue from "vue";
import Router from "vue-router";

Vue.use(Router);

export default new Router({
  routes: [
    {
      path: "/login",
      name: "Login",
      component: () => import("./views/Login.vue")
    },
    {
      path: "/",
      name: "Home",
      component: () => import("./views/Home.vue")
    }
  ]
});

(2) 添加登录页 新建文件 -- src/views/Login.vue

<template>
  <div>
    <div>test</div>
    <div>
      <div>
        <label for="name">用户名</label>
        <input type="text" name="name" v-model="user.name">
      </div>
      <div>
        <label for="password">密码</label>
        <input type="password" name="password" v-model="user.password">
      </div>
      <button @click="userLogin">登录</button>
      <div>{{token}}</div>
    </div>
  </div>
</template>

<script>
import userApi from "@/api/userApi";
import { mapGetters } from "vuex";
export default {
  data() {
    return {
      user: {
        name: "",
        password: ""
      }
    };
  },
  computed: {
    ...mapGetters(["token"])
  },
  methods: {
    async userLogin() {
      let res = await userApi.login(this.user);
      if (res) {
        this.$store.dispatch("setToken", res.result.token);
        this.$router.push({ path: this.redirect || "/" });
      }
    }
  }
};
</script>

(3) 添加首页 新建文件 -- src/views/Home.vue

<template>
  <div>
    <div>Home</div>
    <div>
      <div>
        <span>用户名:</span>
        {{userInfo.name}}
      </div>
      <div>
        <span>权限:</span>
        {{userInfo.auth}}
      </div>
      <div>
        <span>账户创建时间:</span>
        {{userInfo.time}}
      </div>
    </div>
    <button @click="userLogout">退出登陆</button>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  computed: {
    ...mapGetters(["userInfo"])
  },
  methods: {
    userLogout() {
      this.$store.dispatch("logOut").then(() => {
        location.reload(); // 为了重新实例化vue-router对象 避免bug
      });
    }
  }
};
</script>
9.引入权限--最终效果预览
//main.js
import "@/permission";

效果预览

效果预览

六、打包部署

npm run build

部署可选择手动打包也可以用jenkins自动打包 jenkins自动打包教程 源码 项目预览 登录账号密码随意填 项目接口用的是easy-mock的服务,偶尔会500造成接口请求报错,如果遇到就等一会重新试下~~

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券