Vue 项目搭建教程


Vue 作为当下前端三巨头之一,在易上手方面有着独特的优势,下面就让我们学习如何从零搭建 Vue 2 项目,并基于 Axios 实现与后端的请求访问。

一、项目创建

1. 环境准备

先检查自己是否已经安装了 node ,没有的话先到官网下载之后无脑下一步即可。

node -v     # 查看Node版本

npm -v      # 查看NPM版本

完成 node 安装之后可同步安装 cnpm,器为阿里的 npm 镜像,在网络不佳时可替代 npm 实现依赖下载。

npm install -g cnpm --registry=http://registry.npm.taobao.org    

cnpm -v     # 查看cnpm版本

2. 新建工程

完成环境准备工作之后便可创建具体的项目,根据你的喜好选择对应目录,新建命令行窗体运行如下命令:

# 初始化项目
vue init webpack my-project

回车后便会自动下载项目模板内容,期间会让你输入项目描述。

注意选择 ESLint 的时候记得选 no ,否则后续格式会出现奇奇怪怪的格式错误,具体提示信息如下:

Project name <你的项目名>
Project description <你的项目描述>
Author <作者>
Vue build standalone

# 是否生成 router 目录
Install vue-router? Yes

# 是否引入 ESlint
Use ESLint to lint your code? No

# 是否生成单元测试
Set up unit tests No

# 是否生成单元测试
Setup e2e tests with Nightwatch? No

# 是否在项目创建后运行 npm install
Should we run `npm install` for you after the project has been created? (recommended) npm

二、样式引入

1. 依赖安装

Vue 生态中拥有丰富的 UI 框架库,最出名的莫过于 Element UIAnt Design,提供了更丰富的组件样式。

这里以阿里的 Ant Design 为例,步骤基本相似可根据自身偏好选择。

在工程目录下新建命令窗口运行如下命令下载依赖。

npm i --save ant-design-vue 

2. 依赖导入

依赖下载完成后找到 src/main.js 文件全局导入样式,当然你也可以在对应的页面按需引入。

// 全局引入样式
import Antd from 'ant-design-vue';
import 'ant-design-vue/dist/antd.css';

Vue.use(Antd);

三、Axios配置

1. 安装配置

Axios 是一个基于 promise 网络请求库,常用于前后端分离项目中,下面就让我们了解如何进行配置。

打开之前新建的工程根目录,运行如下命令安装 Axios

npm install axios

完成后在 src 目录下新建 api 目录,并在目录下新建 axios.js 文件用于封装请求处理。

代码配置如下,其中 baseURL 即为前端服务地址,timeout 则为请求后端接口超时时间。

import Vue from 'vue';
import axios from 'axios';

function request(axiosConfig) {
    const service = axios.create({
        baseURL: 'http://localhost:9090',     // 设置统一的请求前缀
        timeout: 60000,                       // 设置统一的超时时长, 单位毫秒
    });

    // 请求处理
    service.interceptors.request.use(config => {
        return config
    }, err => {
        console.log(err);
    })

    // 响应拦截
    service.interceptors.response.use(res => {
        if (res === null || res.data === undefined || res.data === null) {
            return null
        }

        return res.data
    }, err => {
        // 请求信息弹窗提示
        const errMsg = err.response.data
        Vue.prototype.$notification['error']({
            message: 'Internal Server Error',
            description: errMsg.error,
        });
    })

    return service(axiosConfig)
}

export default request;

2. 后端对接

找到项目下的 config/index.js 文件,按照下述配置模板调整文件内容:

module.exports = {
  dev: {
    host: "<前端地址>",
    port: <前端端口>, 
    proxyTable: {
      "<前端请求前缀>": {
        target: '<后端服务地址>',
        changeOrigin: true,
        pathRewrite: {
          '^<前端请求前缀>': '<后端请求前缀>'
        }
      }
    }
  }
}

其中 <后端请求前缀> 通常即 Spring 项目中 servlet.context-path,若无则为配置为 /

如下配置效果即 http://localhost:8080/web-demo/xxx 将转发至 http://localhost:9090/webDemo/xxx

module.exports = {
  dev: {
    host: "localhost",
    port: 8000, 
    proxyTable: {
      "web-demo": {
        target: "localhost:9090",
        changeOrigin: true,
        pathRewrite: {
          "^/web-demo": "/webDemo"
        }
      }
    }
  }
}

完成配置后回到刚才 axios.js 文件中将 baseURL 的值替换成上述的 <前端请求前缀>

const service = axios.create({
    baseURL: '/web-demo',
    timeout: 60000,
});

四、接口请求

1. 基本格式

接下来我们了解 Axios 请求方法的格式,主要有以下两种方式,区别在于方式一是将参数通过请求体进行发送,而后者则是将参数自动拼接在 URL 中。

export function <function name> (params) {
  return request({
    url: '<request url>',
    method: 'type',
    data: params
  })
}

export function <function name> (params) {
  return request({
    url: '<request url>',
    method: '<type>',
    params: params
  })
}

2. Get请求

Get 请求中常通过 params 方式传参,假设后端存在下述接口:

@GetMapping("/get")
public User get(@RequestParam(name = "id") String id) {
    // do something
    
}

前端在 Axios 中则可通过下述方式以参数拼接形式发起请求。

export function get(params) {
    return request({
        url: `/users/get?id=${params}`,
        method: 'get'
    })
}

若需传入多个参数时显然一一手动拼接并不合适,Axios 同样支持传入一个对象。

export function get(params) {
    return request({
        url: '/users/get',
        method: 'get',
        params: params
    })
}

3. Post请求

同理,针对 Post 请求后端通过 @RequestBody 注解标识接收 Json 数据。

@PostMapping("/add")
public int add(@RequestBody User user){
    // do something

}

相对应的在 Axios 中请求方式如下:

export function add(params) {
    return request({
        url: '/users/add',
        method: 'post',
        data: params
    })
}

参考链接:

  1. Axios二次封装
  2. 源码:Axios封装

文章作者: 烽火戏诸诸诸侯
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 烽火戏诸诸诸侯 !
  目录