In Vue project, set axios global, Iview this.$Notice (Message), etc., in main.js, which cannot be used.

as the title

part of the code that implements the this.$Notice of Iview (some information is not convenient to display, sorry)

clipboard.png

Notice,

clipboard.png

what to do with this? the native alert can be used normally, but the style is ugly and the customization is troublesome. Coupled with the use of Iview UI, there is no need to do it yourself

.
Jun.18,2022

because the this at this time does not point to the vue instance, so you can not find this method, you can directly

import { Notice } from 'iview'

Notice.warning()

this is the answer to someone else's question before. forgive me for copying it directly

.

the original text is as follows:

personally, you are not recommended to send a request in this way. I hope you can read on, a relatively simple

you should be like this.

A method axios.js that separately encapsulates an axios request contains the post,get,fromdate request method.

// axios.js 
import axios from 'axios';
import Cookies from 'js-cookie';

axios.defaults.timeout = 9999999;
axios.defaults.baseURL ='';


//http request 
axios.interceptors.request.use(
  config => {
    let token = Cookies.get('token'); //cookiejs-cookie
    
    if(config.method=='post'){ // post token
        config.data = config.data;
        if(token){
          config.data.token = token
        } 
        // else {
        //   console.log('token')
        // }
        config.headers = {
        'Content-Type':'application/x-www-form-urlencoded',
        }
    } else if(config.method=='get'){ // get url
        config.params.token = token
        config.headers = {
            'Content-Type':'application/x-www-form-urlencoded',
        }
    }
    return config;
  },
  error => {
    return Promise.reject(err);
  }
);


//http response 
axios.interceptors.response.use(
    // token 
  response => {
    if(response.data.errCode ==2){
      router.push({
        path:"/login",
        querry:{redirect:router.currentRoute.fullPath}//
      })
    }
    return response;
  },
  error => {
    return Promise.reject(error)
  }
)


/**
 * get
 * @param url
 * @param data
 * @returns {Promise}
 */
export function get(url,params={}){
  return new Promise((resolve,reject) => {
    axios({
        url: url,
        method: 'GET',
        params: params,
        transformRequest: [function (data) {
          let ret = ''
          for (let it in data) {
            ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
          }
          return ret
        }],
        })
        .then(res => {
            if(res.data.code == 1001){
                this.$Message.warning(',' + res.data.message);
                this.$router.push({path:'/'})
                return
            }
            resolve(res.data);
        })
        .catch(err => {
            reject(err)
        })
  })
}


/**
 * post
 * @param url
 * @param data
 * @returns {Promise}
 */
 export function post(url,data = {}){
   return new Promise((resolve,reject) => {
        axios({
        url: url,
        method: 'POST',
        data: data,
        transformRequest: [function (data) {
          let ret = ''
          for (let it in data) {
            ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
          }
          return ret
        }],
        })
        .then(res => {
            if(res.data.code == 1001){
                this.$Message.warning('' + res.data.message);
                this.$router.push({path:'/'})
                return
            }
            resolve(res.data);
        })
        .catch(err => {
            reject(err)
        })
   })
 }

 /**
  * from 
  */
 export function get_from(URL, PARAMS) {
  var p = new Promise((resolve, reject) =>{        //
    var temp = document.createElement("form");
    temp.action = URL;
    temp.method = "get";
    temp.style.display = "none";
    for (var x in PARAMS) {
      var opt = document.createElement("textarea");
      opt.name = x;
      opt.value = PARAMS[x];
      temp.appendChild(opt);
    }
    document.body.appendChild(temp);
    temp.submit();
    this.$Loading.finish();
    resolve(temp) 
  });
  return p;
}

/**
 *  excel
 */

export function up_excel(URL, PARAMS) {
  return new Promise((resolve,reject) => {
    let token = this.$Cookies.get('token')
    let config = {
        headers: {
        'Content-Type': 'multipart/form-data'
        }
    }
    PARAMS.append('token', token)

    axios.post(URL, PARAMS, config)
      .then( res => {
        resolve(res.data)
      })
      .catch(err=>{
        reject(err)
      })
  })
}

then expose the methods in axios.js in main.vue. Then register globally for use (as below)

import {post,get,get_from,up_excel} from './api/axios'
Vue.prototype.$get=get;
Vue.prototype.$get_from = get_from;
Vue.prototype.$up_excel = up_excel;

at this point, you can use it again in the component. The methods used are

// url:   data:
this.$post(url,data)
    .then(res=>{
        if(res.code == 200){
            // 
        } else {
            // 
        }
    })
    
 this.$get(url,data)
    .then(res=>{
        if(res.code == 200){
            // 
        } else {
            // 
        }
    })
   

ps: I personally like to put the whole interface in a file like this linkUrl.js

let main = ''

const linkurl = {
    login : main + '/login/login',
}

export default linkurl

then register globally

import linkurl from './api/LinkUrl'

Vue.prototype.$linkurl = linkurl

at this time, you can use this directly in the encapsulated request

this.$post(this.$linkurl.login, data)  // this.$linkurl.loginjs
    .then(res=>{
        if(res.code == 200){
            // 
        } else {
            // 
        }
    })
    

1, quote import {Notice} from 'iview'; , then Notice.warning ()
2, Vue.prototype.$Notice try.
the this does not point to the vue instance at this time in main.js, so an error will be reported if you write it this way.


if you use the entire iView. You can use Vue.$Notice.warning ()

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1c15ec4-32fcf.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1c15ec4-32fcf.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?