Scaffolding vue-cli packaging items and Axios

Fourth, the installation vue-cli scaffolding building tools

Global installed, the command line

npm install -g vue-cli

Vue -V command line view the version number, the version number is the successful installation appears

Five, vue-cli building project

Into your project directory, create a new project based webpack template: vue init webpack project name

vue init webpack demo

Where the demo is the name of the project, according to their own project definition name, press the Enter key, the template will be downloaded into the series of configuration issues

Description:

Project name: Project Name

  • Project description: Project Description 
    Author: Author 
    Vue build: a packaging (standalone and runtime), press Enter to select the default like 
    the Install VUE -router? : Whether to install the route? Definitely need to use, press Enter y 
    the Use ESLint to lint your code ? : Are eslint code detection rules enabled? Currently not need, press the Enter n 
    Setup Unit Tests with Karma + Mocha? : Whether the unit test? Currently not need, press the Enter n 
    Setup E2E Tests with Nightwatch :?-End whether to test? Currently not need, press the Enter n

     

After configuration is complete we will see our project file demo, we can locate the terminal to the current project, and enter the following command line command line in your project directory, the project started successfully. In the browser address bar enter localhost: 8080 can access project

npm run dev

Six, vue project catalog description

1, build: build scripts directory

    1) build.js ==> the production environment build script;

    2) check-versions.js ==> Check npm, node.js version;

    3) utils.js ==> Construction related utility;

    4) adding the prefix automatically after vue-loader.conf.js ==> css loader configured to compile and css;

    5) webpack.base.conf.js ==> webpack basic configuration;

    6) webpack.dev.conf.js ==> webpack development environment configuration;

    7) webpack.prod.conf.js ==> webpack production environment configuration;

2, config: project configuration

    1) dev.env.js ==> Development Environment variables;

    2) index.js ==> Project Profiles;

    3) prod.env.js ==> production environment variable;

3, node_modules: npm module loaded project dependencies

4, src: here is we want to develop the directory, basically things to do in this directory. Which contains a number of directories and files:

    1) assets: resource directory, place some pictures or public js, public css. Resources here will be constructed webpack;

    2) components: Component catalog, we write it in this directory components inside;

    3) router: front-end routing, routing path we need to be configured to write index.js inside;

    4) App.vue: root component;

    5) main.js: js file entry;

5, static: static resource directory, such as images, fonts and so on. Will not be built webpack

6, babelrc: babel translation parameters

7, editorconfig: code format

8, gitignore: git upload the configuration file to be ignored

9, postcssrc.js: css conversion tool

10, index.html: Home entrance file, you can add some meta information,

11, package.json: npm package configuration file that defines script npm project, dependent packages and other information

12, README.md: documentation project, markdown format

Seven, modify the port the port number

To avoid port conflicts, you can modify the port, open the config / index.js file, modify port parameters

Eight, installation element-ui framework

[1] Installation

npm install element-ui -S

[2] introduced in main.js file

import ElementUI from 'element-ui'

import 'element-ui/lib/theme-chalk/index.css'

Vue.use(ElementUI)

 

Nine, install sass

[1] Installation

npm install --save-dev css-loader
npm install --save-dev sass-loader
npm install --save-dev style-loader

//sass-loader依赖于node-sass
npm install --save-dev node-sass

[2] Configuration

Folder configuration in webpack.base.conf.js

rules:[
    ....
    {
        test: /\.sass$/,
        loaders: ['style', 'css', 'sass']
    }
]

【3】测试

在要用到scss的组件里面的style标签上加上 lang='scss'

在app.vue文件定义一个背景颜色变量,应用到css样式中,背景变成灰色,说明已成功配置好sass

十、配置本地代理

1、在项目找到config/index.js文件对proxyTable进行配置,配置完成后需要npm run dev重启一下项目

 proxyTable: {
      '/api': {           // 配置后台代理
        target: 'http://192.168.37.56:8090',
        secure: false,
        pathRewrite: {
          '^/api': ''
        },
        changeOrigin: true
      },
      "/socket": {       // 配置webSocket
        target: 'http://192.168.37.56:8090',
        secure: false,
        pathRewrite: {
          '^/socket': ''
        },
        changeOrigin: true,
        ws: true
      },
    }

说明:

  • target:本地测试环境请求后台接口的域名ip
  • secure:https需要配置的参数
  • pathRewrite:代替targe里面的地址,比如我们需要调用"http:192.168.37.56:8090/user/add"接口,我们可以直接写成"/api/user/add"
  • changeOrigin:接口跨域需要配置的参数

2、config/index.js配置参数的详细解析

'use strict'
const path = require('path')

module.exports = {
  // 开发环境
  dev: {
    assetsSubDirectory: 'static', // 编译输出的二级目录
    assetsPublicPath: '/',  // 编译发布的根目录,可配置为资源服务器域名或CDN域名
    proxyTable: {}, // 配置后台代理
    host: 'localhost', // 运行测试页面的域名ip
    port: 8080,  // 运行测试页面的端口
    autoOpenBrowser: false, // 项目运行时是否自动打开浏览器
    errorOverlay: true, // 浏览器错误提示
    notifyOnErrors: true, // 跨平台错误提示
    poll: false, // 使用文件系统获取文件改动的通知devServer.watchOptions
    devtool: 'cheap-module-eval-source-map', // 增加调试,该属性为原始源代码
    cacheBusting: true, // 使缓存失效
    cssSourceMap: true // 代码压缩后bug定位将非常困难,引入SourceMap记录压缩前后的位置信息记录,当产生错误时直接定位到压缩前的位置
  },
  // 生产环境
  build: {
    index: path.resolve(__dirname, '../dist/index.html'), // 编译输入的index.html文件
    assetsRoot: path.resolve(__dirname, '../dist'), // 编译输出的静态资源路径(项目打包时的文件)
    assetsSubDirectory: 'static', // 编译输出的二级目录
    assetsPublicPath: '/', // 编译发布的根目录,可配置为资源服务器域名或CDN域名
    productionSourceMap: true, // 是否开启cssSourceMap
    devtool: '#source-map', // 增加调试,该属性为原始源代码
    productionGzip: false, // 是否开启gzip
    productionGzipExtensions: ['js', 'css'], // 需要使用gzip压缩文件的扩展名
    bundleAnalyzerReport: process.env.npm_config_report // 打包分析
  }
}

 

十一、axios的封装

【1】安装

npm install axios --save-dev复制代码

【2】在项目的src目录下新建一个services文件夹,然后在里面新建一个ajax.js和一个getData.js文件。ajax.js文件用来封装我们的axios,getData.js用来统一管理我们的接口。

 

 

【3】ajax.js 封装axios

import axios from "axios";
import store from "@/store";
import { Message } from "element-ui";
let router = import("@/router");

axios.defaults.baseURL = "/api";
axios.defaults.headers.post["Content-Type"] = "application/json;charset=UTF-8";
axios.defaults.headers["X-Requested-With"] = "XMLHttpRequest";
axios.defaults.headers["Cache-Control"] = "no-cache";
axios.defaults.headers["pragma"] = "no-cache";

let source = axios.CancelToken.source();

//请求添加token
axios.interceptors.request.use(request => {
    request.headers["demo-auth"] = store.state.loginInfo ? store.state.loginInfo.userId : ""; // 已将userId保存在store中
    return request;
})

//切换页面取消请求
axios.interceptors.request.use(request => {
    request.cancelToken = source.token;
    return request;
});
router.then(lib => {
    lib.default.beforeEach((to, from, next) => {
        source.cancel()
        source = axios.CancelToken.source();
        next()
    })
})

//登录过期跳转
axios.interceptors.response.use(response => {
    let data = response.data;
    if (
        [10002].includes(data.ret)
    ) {
        router.then(lib => lib.default.push({ name: "login" })); // 跳转到登录页面
        Message.warning(data.msg);
    }
    return response;
})

//返回值解构
axios.interceptors.response.use(response => {
    let data = response.data;
    let isJson = (response.headers["content-type"] || "").includes("json");
    if (isJson) {
        if (data.code === 200) {
            return Promise.resolve({
                data: data.data,
                msg: data.msg,
                code: data.code,
            });
        }
        return Promise.reject(
            data.msg ||
            "网络错误"
        );
    } else {
        return data;
    }
}, err => {
    let isCancel = axios.isCancel(err);
    if (isCancel) {
        return new Promise(() => { });
    }
    return Promise.reject(
        err.response.data &&
        err.response.data.msg ||
        "网络错误"
    );
})

export function post(url, data, otherConfig) {
    return axios.post(url, data, otherConfig);
}

export function get(url, data, otherConfig) {
    return axios.get(url, { params: data, ...otherConfig });
}

【4】getData.js 接口管理

import { get, post } from "@/services/ajax";

//获取程序配置
export function getConfig() {
    return get("static/config.json", null, { baseURL: "./" });
}

// 查找货物已占用位置
export function queryGoodsLabel(params) {
    return get("/goods/queryGoodsLabel", params);
}

// 更换货物已占用位置
export function switchLabel(params) {
    return post("/goods/switchLabel", params);
}
}

 

【5】在页面中调用

import { queryGoodsLabel, switchLabel } from '@/services/getData.js'
export default {
        data() {
            return {}
        },
        methods: {
            changePlace(row) {
                this.params = {
                    id: row.id,
                    customsListNumber: row.customsListNumber,
                }

                // 查找货物已占用位置
                queryGoodsLabel(this.params).then(res => {
                    this.$refs.positionDialog.refill(res.data.split(","), true);
                }).catch(err => {

                })
            },
            change(data) {
                this.params.labels = data.join(',')

                // 更换货物已占用位置
                switchLabel(this.params).then(res => {
                    this.$Message.success('更换位置成功')
                }).catch(err => {
                    this.$Message.error(err)
                })
            }
        },
    }

 

 

Guess you like

Origin www.cnblogs.com/xiaolucky/p/11579929.html