vue-cli@4 入门(二)

根据上一篇文章,我们的项目已经可以运行了。为了开发方便,我们这里使用 element-UI

在操作之前,先简单介绍一下 npm run serve

打开项目,在项目根目录下,有一个 package.json 文件。

可以发现 scripts 下面, 有 serve, build 等命令。这里和我们运行 的 npm run serve相对应

npm run build 就是打包了。这里也可以自己拓展功能

1
2
3
4
5
6
"scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "test:unit": "vue-cli-service test:unit",
    "lint": "vue-cli-service lint"
  },

安装element-UI

终端命令, cd 到项目的根目录

$ cd projectName
$ vue add element
$ 然后输入 y 回车
# 为了方便,选择第一个全局引用:Fully import
? How do you want to import Element? (Use arrow keys)
❯ Fully import 
  Import on demand 
# 选择 y
? Do you wish to overwrite Element's SCSS variables? (y/N)   
# 选择 zh-CN
? Choose the locale you want to load (Use arrow keys)
❯ zh-CN 
zh-TW 
af-ZA 
ar 
bg 
ca 
cs-CZ

等待安装结束,然后在项目src目录下 main.js中添加

import ElementUI from "element-ui"; //element-ui的全部组建
Vue.use(ElementUI); //使用elementUI
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import './plugins/element.js'

# 这里添加就可以了
import ElementUI from "element-ui"; //element-ui的全部组建
Vue.use(ElementUI); //使用elementUI

Vue.config.productionTip = false

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

安装less依赖

npm install less less-loader --save-dev

如果提示错误:

ERROR  Failed to compile with 1 errors  	
执行
npm install sass-loader -D

Mac下修改目录 (Windows不清楚,应该类似,进入安装的程序目录) /Applications/IntelliJ IDEA.app/Contents/plugins/JavaScriptLanguage/languageService/eslint/bin 下的 eslint-plugin.js 25行为:

this.cliEngine = require(this.basicPath + "lib/cli-engine").CLIEngine;

vue.config.js

配置域名,跨域,新建项目的时候是没有这个文件的,需要自己创建一个。在项目根目录下创建 vue.config.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
module.exports = {
    //编译打包存放的目录默认dist
    outputDir: 'dist',

    // 如果你不需要使用eslint,把lintOnSave设为false即可
    lintOnSave: false,

    // 设为false打包时不生成.map文件
    productionSourceMap: false,

    assetsDir: 'static',
    /*css: {
      loaderOptions: {
        css: {},
        postcss: {
          plugins: [
            // 补全css前缀(解决兼容性)
            require("autoprefixer")(),
            // px单位换算成rem单位
            require("postcss-pxtorem")({
              rootValue: 32, // 换算的基数(设计图750的根字体为32)
              selectorBlackList: [".van", ".my-van"],// 要忽略的选择器并保留为px
              propList: ["*"], //可以从px更改为rem的属性
              minPixelValue: 2 // 设置要替换的最小像素值。
            })
          ]
        }
      }
    },*/

    devServer: {
        port: 8089,
        proxy: {/*处理跨域,本地代理转发*/
            '/proxy': {
                target: 'http://localhost:8080',  // 接口域名
                secure: false,  // 如果是https接口,需要配置这个参数
                changeOrigin: true,  //是否跨域
                pathRewrite: {
                    '^/proxy': ''
                }
            },
            '/video': {
                target: 'http://192.168.2.132:8081',  // 接口域名
                secure: false,  // 如果是https接口,需要配置这个参数
                changeOrigin: true,  //是否跨域
                pathRewrite: {
                    '^/video': ''
                }
            },
        },
        // 禁用主机检查
        disableHostCheck: true
    }
}

axios 网络请求

由于axios是需要打包到生产环境中的,所以我们使用–save来进行安装

npm install axios --save

加载 es6-promise

npm install --save es6-promise

一、直接使用

main.js 中 插入以下内容,就可以全局通过 this.$axios调用

import axios from 'axios'
Vue.prototype.$axios = axios

npm i -g node-sass

npm audit fix --force

二、进行封装使用

src/api/ 目录下创建一个 public.js(自己起个名就好)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
require('es6-promise').polyfill()
import axios from 'axios'
axios.defaults.withCredentials = true //跨域
axios.defaults.timeout = 60000
axios.defaults.headers.post['Content-Type'] = 'application/x-www=form-urlencoded'
export default {
  //get请求
  requestGet (url, params = {}) {
    return new Promise((resolve, reject) => {
      axios.get(url, params).then(res => {
        resolve(res.data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  //get请求不带参数
  requestQuickGet (url) {
    return new Promise((resolve, reject) => {
      axios.get(url).then(res => {
        resolve(res.data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  //post请求
  requestPost (url, params = {}) {
    return new Promise((resolve, reject) => {
      axios.post(url, params).then(res => {
        resolve(res.data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  //post请求
  requestPostForm (url, params = {}) {
    return new Promise((resolve, reject) => {
      axios.post(url, params, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
      }).then(res => {
        resolve(res.data)//注意res是axios封装的对象res.data才是服务端返回的信息
      }).catch(error => {
        reject(error)
      })
    })
  },
  //put请求
  requestPut (url, params = {}) {
    return new Promise((resolve, reject) => {
      axios.put(url, params).then(res => {
        resolve(res.data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  //delete请求
  requestDelete (url, params = {}) {
    return new Promise((resolve, reject) => {
      axios.delete(url, params).then(res => {
        resolve(res.data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  exportExcel: function(url,form) {
    return axios({ // axios发送post请求
      method: 'get',
      url: url, // 请求地址
      data: form, // 参数
      responseType: 'blob', // 表明返回服务器返回的数据类型
      headers: {
        'Content-Type': 'application/json'
      }
    })
  }
}

src/api/ 目录下创建一个 api.js(自己起个名就好)

//将前面封装的 axios 引入到 api.js 中
import http from './../api/public'
//用户登录
// /proxy 这个是 跨域的时候配置的vue.config.js的跨域字符 /proxy
//比如 localhost:8080/api/user/login 跨域写成  => /proxy/api/user/login
export const login = params =>{
	return http.requestPost('/proxy/api/user/login',params)
}
Licensed under CC BY-NC-SA 4.0
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy