1. 程式人生 > >Vue Vuex和axios的安裝及使用(入門級)axios的簡單封裝

Vue Vuex和axios的安裝及使用(入門級)axios的簡單封裝

前言:之所以將Vuex和axios一起講,是因為,請求伺服器之後需要儲存一些全域性狀態,全域性屬性等
一 、axios的安裝
執行 → cmd回車 → 進入專案路徑 → 執行以下命令
npm install axios

二、Vuex的安裝
執行 → cmd回車 → 進入專案路徑 → 執行以下命令
npm install vuex –save

注意:使用store.commit(‘函式名’,函式中的引數名)——這裡的“,函式中的引數名”,定義的引數名與實際的引數名需要一致,否則會報錯:null

三、axios的使用及封裝(除了上傳檔案,一般是夠用了)
① 在這裡我建立了一個http資料夾,新建一個httpRequestUtil.js檔案,內容如下:

import axios from 'axios'
import store from '../store'

/**
 * 使用Vuex的store之前需要先引入,
 * 1.通過store.state.tokenStr獲取屬性值
 * 2.通過store.commit('mutations中的方法名',tokenStr)設定屬性值
 */

function initAxios() {//初始化配置
  //設定api訪問基路徑
  axios.defaults.baseURL = 'http://121.11.2012iot.com/';
  axios.defaults.headers.common['tokenStr'
] = store.state.tokenStr;//這裡使用了Vuex中的常量(需要先引入store) axios.defaults.headers.post['Content-Type'] = 'application/json'; } /** * 說明:我這裡預設的伺服器返回的最外層物件如下, * {code: 0, message: null, obj: "1766", tokenStr: "MTc2Nl90b2tlbl8tMTUzMDY5MTE3MTMxNA=="} * 如果你們的伺服器返回不是這樣,需要在 backview 方法中做相應的更改 * * catch 1.捕獲請求異常 * 2.捕獲處理異常【包含response使用不當】 * * * 提交表單 * let formData = new FormData(); * formData.append('name', this.name); * formData.append('age', this.age); * formData.append('file', this.file); * axios.post(hasParamUrl, params).then(function (response){}catch(error){} * */
/** * GET 方式請求資料 * @param hasParamUrl 請求url(已經拼接好的路徑) * @param callback 回撥函式 */ export function getData(hasParamUrl, callback) { if (hasParamUrl == null) return initAxios(); axios.get(hasParamUrl).then(function (response) { backView(response, callback) }).catch(function (error) { callback(null, "請求報錯") console.log(error); }) } /** * POST 方式請求 * @param hasParamUrl 請求url * @param params (如下的param) * var param = new URLSearchParams; * param.append("name", "mirzhao"); * @param callback 回撥函式 */ export function postData(requestUrl, params, callback) { initAxios(); axios.post(requestUrl, params).then(function (response) { store.commit("setTokenStr", response.data.tokenStr)//儲存token到Vuex的state backView(response, callback) }).catch(function (error) { callback(null, "請求報錯") console.log(error); }) } /** * POST 方式請求(傳送到伺服器的是一個json物件) * @param requestUrl 請求url * @param params (如下的param) * var param = new URLSearchParams; * param.append("name", "mirzhao"); * @param callback 回撥函式 */ export function postStringParamData(requestUrl, params, callback) { initAxios(); axios.post(requestUrl, JSON.stringify(params)).then(function (response) { backView(response, callback) }).catch(function (error) { callback(null, "請求報錯" + error) console.log(error); }) } /** * 上傳檔案——可以同時上傳多個 * @param uploadFileUrl * @param formData * let formData = new FormData(); //建立form物件 * param.append('file',file1,fileName1);//通過append向form物件新增資料 * param.append('file',file2,fileName2);//通過append向form物件新增資料 * param.append('file',file3,fileName3);//通過append向form物件新增資料 */ export function postFile(uploadFileUrl, formData, callback) { let config = { headers: {'Content-Type': 'multipart/form-data'} } axios.post(uploadFileUrl, formData, config).then(function (response) { backView(response, callback) }).catch(function (error) { callback(null, "請求報錯" + error) console.log(error); }) } /** * 獲取到資料後——統一處理最外層物件 * @param response * @param callback */ function backView(response, callback) { console.log(response.data);//列印返回的資料實體 reponse.data才是伺服器返回的資料 if (response != null && response.data != null && response.data.code == 0) { console.log("請求成功") store.commit("setTokenStr", response.data.tokenStr) if (callback != null) { callback(response.data.obj, null) } } else { console.log("請求失敗") if (callback != null) { callback(null, response.data.message) } } } // console.log(response.status);//伺服器返回的狀態 // console.log(response.statusText); // console.log(response.headers); // console.log(response.config); export default { getData, postData, postStringParamData, postFile }

② 呼叫

<template>
  <div>
    <div id="box">
      <div style="margin-top: 20px">
        <button id="testGet" v-on:click="testget">測試GET方法</button>
        <button id="testPost" v-on:click="testpost">測試POST方法</button>
        <button id="testPostStringParam" v-on:click="testpoststring">測試POST-String方法</button>
      </div>
      <div style="margin-top: 0px">
        <span id="testGet_span">測試GET方法-返回:{{getdataS}}</span>
        <span id="testPost_span">測試POST方法-返回:{{postDataS}}</span>
        <span id="testPostStringParam_span">測試POST-String方法-返回:{{postDataStringS}}</span>
      </div>
    </div>
  </div>
</template>

<script>
  import httpUtil from '../http/httpRequestUtil'

  export default {
    name: "findpwd",
    data() {
      return {
        getdataS: '',
        postDataS: '',
        postDataStringS: ''
      }
    },
    methods: {
      testget: function (res) {
        console.log("測試GET方法");
        var that = this;
        var url = "api-common/user/getUserInfo";
        httpUtil.getData(url, function (data, message) {
          console.log(data)
        })
      },
      testpost: function (res) {
        console.log("測試POST方法");
        var url = "api-common/user/updateUserName";
        var param = new URLSearchParams;
        param.append("name", "mirzhao");
        httpUtil.postData(url, param, function (data, message) {
          console.log(data)
        })
      },
      testpoststring: function (res) {
        console.log("測試POST-String方法");
        var url = "api-common/companyConf/updateCompanyConf";
        var param = new URLSearchParams;
        param.append("mtcRemind", "14");
        httpUtil.postStringParamData(url, param, function (data, message) {
          console.log(data)
        })
      },
    },
    created: function (res) {

    }
  }
</script>

<style scoped>
  #box {
    width: 800px;
    height: 320px;
    position: absolute;
    top: 50%;
    margin-left: 50%;
    left: -400px;
    margin-top: -160px;
    border: orange solid 2px;
    display: flex;
    flex-direction: column;
    text-align: center;
  }

  span {
    font-size: 14px;
    color: black;
  }
</style>

二、Vuex的
1.Vuex使用及配置
①建立一個資料夾store,在其中建立index.js檔案,內容如下:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state = {
  tokenStr: '',

  userName: '',
  userPhone: '',
  userUuid: '',
  userHeadPath: '',
  userBirthday: '',
  userIdNum: '',//身份證號碼
  userSex: '',//1男,2女

  companyId: '',
  companyName: '',
  companyType: '',

  userRole: ''
}
export const mutations = {
  setTokenStr(state, tokenStr) {//設定tokenStr的值
    state.tokenStr = tokenStr
  },
  setUserUuid(state, userUuid) {
    state.userUuid = userUuid
  },
  setUserInfo(state, userInfo) {
    state.userName = userInfo.userName;
    state.userBirthday = userInfo.dayOfBirth;
    state.userPhone = userInfo.phoneNumber;
    state.userHeadPath = userInfo.headerPath;
    state.userSex = userInfo.sex;
    state.userIdNum = userinfo.idNumber;
    state.companyId = userInfo.companyId;
  },
  setUserRole(state, userRoleStr) {
    state.userRole = userRoleStr;
  },
  setUserCompanyInfo(state, companyInfo) {
    state.companyName = companyInfo.name;
    state.companyType = companyInfo.conpanyType;
  }
}

export default new Vuex.Store({
  state,
  mutations
})

② 在main.js中匯入並配置到vue例項中

import Vue from 'vue'

import VueRouter from 'vue-router'
import routes from './router/index.js'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'

import store from './store/index'

import header from './components/header.vue'
import footer from './components/footer.vue'

Vue.config.productionTip = false

Vue.component('header-vue', header)
Vue.component('footer-vue', footer)

Vue.use(VueRouter)
Vue.use(ElementUI)
const router = new VueRouter({
  routes
})
new Vue({
  router,
  store,
}).$mount('#app')

2.設定Vuex中的state中的屬性

<template>
  <div>
    <div id="loginbox">
      <div id="logintitle">登入</div>
      <input type="number" v-model="account" placeholder="請輸入您的賬號..."/>
      <input type="password" v-model="pwd" placeholder="請輸入您的密碼..."/>
      <button id="submitbtn" v-on:click="submit">提交</button>
      <div>
        <router-link :to="{path:'register'}" style="font-size: 14px;color: orange;">立即註冊</router-link>
        <router-link :to="{path:'findpwd'}" style="font-size: 14px;color: orange;">找回密碼</router-link>
      </div>
    </div>
  </div>
</template>
<script>
  import axios from 'axios'
  import {hex_sha1} from '../util/sha1'
  import store from '../store'

  export default {
    name: "login",
    data() {
      return {
        visible: true,
        account: '',
        pwd: ''
      }
    },
    created: function () {

    },
    methods: {
      submit: function () {
        if (this.pwd.length == 0 && this.account.length == 0) {
          this.account = "13522224186"
          this.pwd = "00000000"
        }
        var pwd_sha1 = hex_sha1(this.pwd)

        var params = new URLSearchParams();
        params.append('username', this.account);
        params.append('password', pwd_sha1);
        params.append('type', '2');
        //這裡用axios原生的去請求
        axios.post('http://127.112.2012iot.com/api-login/login', params)
          .then(function (respose) {
            console.log(respose.data);
            store.commit("setTokenStr",respose.data.tokenStr)//設定屬性tokenStr的值
          }).catch(function (err) {
          console.log(err)
        })
      }
    }
  }
</script>

<style>
  #logintitle {
    font-size: 22px;
    color: #333;
    margin-top: 20px;
  }

  #loginbox {
    width: 400px;
    height: 320px;
    position: absolute;
    top: 50%;
    margin-left: 50%;
    left: -200px;
    margin-top: -160px;
    border: orange solid 2px;
    display: flex;
    flex-direction: column;
    text-align: center;
  }

  input {
    margin: 10px;
    height: 30px;
    padding-left: 10px;
  }

  input::-webkit-outer-spin-button,
  input::-webkit-inner-spin-button {
    -webkit-appearance: none !important;
    margin: 0;
  }

  #submitbtn {
    height: 30px;
    width: auto;
    margin: 10px;
  }

  .login {
    color: orange;
    font-size: 14px;
  }
</style>

其他:
axios上傳檔案【可以同時上傳多個檔案】【驗證通過,可以正產上傳】
①選擇檔案

<div>
        <input type="file" style="width: auto;height: 50px" multiple="multiple" @change="changeFn($event)"/>
      </div>

②獲取到選擇檔案後返回的檔案,上傳檔案

//選擇圖片返回,上傳檔案
      changeFn(e) {
        let deviceFile = e.target.files;
        let formData = new FormData();
        for (let i = 0; i < deviceFile.length; i++) {
          formData.append("file", deviceFile[0], deviceFile[0].name);
          console.log(deviceFile[i])
        }
        var url = "api-common/filesstorage/uploadFile";
        httpUtil.postFile(url, formData, function (data, message) {
          console.log(data)
        })
      }

實現效果如下
這裡寫圖片描述
這裡寫圖片描述