Axios学习二(在Vue中使用Axios-基于webpack)

一.环境搭建

在前端项目中安装axios,执行:cnpm i axios -S 命令,这样在package.json文件中的依赖devDependencies中多了一个"axios": "^0.19.0",配置。package.json所有配置如下所示:

{
  "name": "webpack-stady",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "build": "webpack",
    "dev": "webpack-dev-server --hot --open --contentBase src --port 8888"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "axios": "^0.19.0",
    "jquery": "^3.4.1",
    "vue": "^2.6.10",
    "vue-router": "^3.0.6"
  },
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-stage-0": "^6.24.1",
    "css-loader": "^2.1.1",
    "file-loader": "^3.0.1",
    "html-webpack-plugin": "^3.2.0",
    "less": "^3.9.0",
    "less-loader": "^5.0.0",
    "style-loader": "^0.23.1",
    "url-loader": "^1.1.2",
    "vue-loader": "^15.7.0",
    "vue-template-compiler": "^2.6.10",
    "webpack": "^4.32.2",
    "webpack-cli": "^3.3.2",
    "webpack-dev-server": "^3.4.1"
  }
}

 

二、封装axios工具类

创建 api.js文件 如下:

import axios from 'axios'
import {getFormData} from './utils.js'

const instance = axios.create({
    baseURL: 'http://localhost:8080',
    timeout:3000
});

export function getRequest(url, params) {
    return instance.get(url, {
        params: params
    })
}

export function postRequest(url, params) {
    return instance.post(url, {
        data: params,
        transformRequest: [function (data, headers) {
            return getFormData(data);
        }]
    });

}

utils.js文件如下:

export function getFormData(param) {
    if (typeof param !== 'object') {
        console.info("传递的参数不是个对象!")
        return;
    }
    if (window.FormData) {
        let formData = new FormData();
        for (let field in param) {
            formData.append(field, param[field]);
        }
        return formData;
    } else {
        let paramArr = [];
        let index = 0;
        for (let field in param) {
            paramArr[index] = encodeURIComponent(field) + "=" + encodeURIComponent(param[field]);
            index++;
        }
        return paramArr.join("&");
    }

}

三、使用

App.vue页面如下





入口文件main.js如下

import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

Vue.config.productionTip = true

import App from './App.vue'
import router from './router.js'

var app = new Vue({
    el: '#app',
    render: h => h(App),
    router
});

Other.vue页面如下





其他文件:router.js如下:

import VueRouter from 'vue-router'

import Account from './components/Account.vue'
import Other from './components/Other.vue'

import login from './components/login.vue'
import register from './components/Register.vue'

var router = new VueRouter({
    routes: [
        {path: '/', redirect: '/other'},
        {path: '/account', component: Account,
            children:[
                {path:'login',component:login},
                {path:'register',component:register}
            ]},
        {path: '/other', component: Other}
    ]
});

export default router

webpack配置和babel配置文件如下:webpack.config.js,.babelrc

const path = require('path');
var htmlWebpackPlugin = require("html-webpack-plugin");
var VueLoaderPlugin = require("vue-loader/lib/plugin");

module.exports = {
    entry: './src/main.js',
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: 'bundle.js'
    },
    plugins: [
        new htmlWebpackPlugin({
            template: path.resolve(__dirname, 'src/index.html'),//模板路径
            filename: 'index.html'
        }),
        new VueLoaderPlugin()
    ],
    module: {
        rules: [
            {test: /\.css$/, use: ['style-loader', 'css-loader']},
            {test:/\.less$/,use:['style-loader', 'css-loader','less-loader']},
            {test: /\.js$/, use: 'babel-loader', exclude: /node_modules/},
            {test:/\.(jpg|png|jpeg|gif|bmp)$/,use:'url-loader?limit=44706&name=[hash:8]-[name].[ext]'},
            { test: /\.(ttf|eot|svg|woff|woff2)$/, use: 'url-loader' }, // 处理 字体文件的 loader
            {test: /\.vue$/, use: 'vue-loader'}
        ]
    }
};
{
  "presets": ["env", "stage-0"],
  "plugins": ["transform-runtime"]
}

四、启动执行

执行npm run dev  结果页面如下:

Axios学习二(在Vue中使用Axios-基于webpack)_第1张图片

 

 

 

你可能感兴趣的:(Axios,Vue,Axios)