Vue+Axios

VUE相关

一、vue中的render (render: h => h(App))

render: h => h(App)是以下缩写

1、基础写法

render: function (createElement) {
    return createElement(App);
}

2、ES6缩写

render (createElement) {
    return createElement(App);
}
render (h){
    return h(App);
}

h 的含义:
来自单词 hyperscript,这个单词通常用在 virtual-dom 的实现中。Hyperscript 本身是指
生成HTML 结构的 script 脚本,因为 HTML 是 hyper-text markup language 的缩写(超文本标记语言)

createElement相当于是操作HTML的DOM元素,Hyperscript
3、ES6箭头函数

render: h => h(App);

4、$mount
参考官方文档: $mount官方文档
Vue.js 里面的 createElement 函数,这个函数的作用就是生成一个 VNode节点,render 函数得到这个 VNode 节点之后,返回给 Vue.js 的 mount 函数,渲染成真实 DOM 节点,并挂载到根节点上。

来自原文:https://blog.csdn.net/MikazukiMo/article/details/106469945

二、jwt_decode中间件

有的时候我们会把 用户的信息 加密到token 返回给前台
前台这块就需要 使用 解析工具将 加密的token 解析 然后拿到用户的信息了

以VUE为例

cnpm i jwt-decode -S

然后就是引入使用 并且 解析你的 token了

import jwt_decode from "jwt-decode";
const decode=jwt_decode(token); // 解析
然后可以将解析完的token 放到 你的vuex中 就可以了

转载:https://blog.csdn.net/yunchong_zhao/article/details/106521100

三、VUEX的store存储

(1)store.commit和store.dispatch的区别及用法
转载:https://blog.csdn.net/AiHuanhuan110/article/details/89160241

四、router.push()实现路由跳转

this.$router.push(location) 修改 url,完成跳转

push 后面可以是对象,也可以是字符串:

// 字符串
this.$router.push('/home/first')
// 对象
this.$router.push({ path: '/home/first' })
// 命名的路由
this.$router.push({ name: 'home', params: { userId: wise }})

例子:
在这里插入图片描述
在这里插入图片描述
图片资源来自:https://www.cnblogs.com/wisewrong/p/6277262.html

五、vue中使用axios调用后端接口

参考并转载自:(1)https://www.jianshu.com/p/cebc90cb2728
(2)https://segmentfault.com/a/1190000016653561

1、封装接口

(1)在api目录下创建两个JS文件,apiURL.js文件存放axios的url路径,http.js文件封装接口
封装接口时需设置响应拦截器和请求拦截器。
封装get和post的例子

/**
 * get方法,对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
function get(url, params = {}) {
	return http({
		url,
		method: 'GET',
		headers: {
			'Content-Type': '请求头',
			'Authorization': 用户验证,可以是存放用户账户信息的token
		},
		params
	})
}
/** 
 * post方法,对应post请求 
 * @param {String} url [请求的url地址] 
 * @param {Object} data [请求时携带的参数] 
 */
function post(url, data = {}) {
	return http({
		url,
		method: 'POST',
		headers: {
			'Content-Type': '请求头',
			'Authorization': localStorage.eleToken
		},
		data:QS.stringify(data)
	})
}

2、axios发送请求,将获得的对象中的字符串变量转化为数组

在axios请求中进行

	this.ad_img = [response.data.item]  //需要转化为数组的字符串只有一组数据(即没有逗号)
	//需要转换为数组的字符串按字符串划分有大于等于1个逗号
	this.imageList = response.data.arrs.split(',')  

六、VUE使用elementUI的$confirm,在.then()后面执行一个异步方法

以axios为例

this.$confirm(msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
        }).then(async() => {   //async必不可少
        //axios的post方法
            _this.$api.post(_this.$apiUrl.maintain{
				num:localStorage.getItem("num"),
			}).then(res =>{
				localStorage.setItem("num",0)
				row.is_issue = localStorage.getItem("num")
			})
            if(msgRet=="Success"){
                self.notify("删除成功!","success",1000);
            }
            else{
                self.notify("删除失败!","warning",1000);
            }
        }).catch(() => {
            console.log("cancel");
    });

七、ref属性

在这里插入图片描述
this.refs的用途
通过this.$refs 可以访问vue实例中所有设置了ref属性的DOM元素,并对其进行操作。
组件中的子组件的ref原理也类似,只是指向的不是原组件而是组件的实例

例子:

<div id="app">
      <input type="text"  alt="captcha"  ref="text">
       <button @click="changeText">change word</button>
 </div>
var app = new Vue({ 
    el: '#app',
    data: {
    },
    //添加一个方法
     methods:{
  //事件
  	change () {
  		//通过this.$refs.text.value获取inout的value的值,并复制给它
  		this.$refs.text.value = 'Helloword'   
  	}
  }
});

参考博客:https://blog.csdn.net/weixin_38981993/article/details/82944629

八、$emit的用法

vm.$ emit( event, arg ) //触发当前实例上的事件
vm.$on( event, fn );//监听event事件后运行 fn;

父组件可以使用 props 把数据传给子组件。子组件可以使用 $emit 触发父组件的自定义事件。
例子:子组件

<template>
  <div class="train-city">
    <h3>父组件传给子组件的toCity:{{sendData}}</h3> 
    <br/><button @click='select(`大连`)'>点击此处将‘大连’发射给父组件</button>
  </div>
</template>
<script>
  export default {
    name:'trainCity',
    props:['sendData'], // 用来接收父组件传给子组件的数据
    methods:{
      select(val) {
        let data = {
          cityname: val
        };
        this.$emit('showCityName',data);//select事件触发后,自动触发showCityName事件
      }
    }
  }
</script>

父组件:

<template>
    <div>
        <div>父组件的toCity{{toCity}}</div>
        <train-city @showCityName="updateCity" :sendData="toCity"></train-city>
    </div>
<template>
<script>
  import TrainCity from "./train-city";
  export default {
    name:'index',
    components: {TrainCity},
    data () {
      return {
        toCity:"北京"
      }
    },
    methods:{
      updateCity(data){//触发子组件城市选择-选择城市的事件
        this.toCity = data.cityname;//改变了父组件的值
        console.log('toCity:'+this.toCity)
      }
    }
  }
</script>

参考博客:https://blog.csdn.net/sllailcp/article/details/78595077

九、父子组件之间的传值

axios

一、拦截器(request和response)

(1)request请求拦截器

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    .....
    return config;
  }, function (error) {
    // 对请求错误做些什么
    ......
    return Promise.reject(error);
    //Promise.reject(reason)返回一个带拒绝原因的的Promise对象
  });

(2)response响应拦截器

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    ....
    return response;
  }, function (error) {
    // 对响应错误做点什么
    ....
    return Promise.reject(error);
  });

补充:error.response.status错误状态码;error.response.msg响应错误信息

二、axios发送请求时params和data的区别

params是添加到url的请求字符串中的,用于get请求。
data是添加到请求体(body)中的, 用于post请求。

转载参考:https://www.cnblogs.com/listen9436/p/11170069.html

三、封装axios的接口

参考:https://www.cnblogs.com/muzishijie/p/11348964.html
文件夹中http.js文件的内容
包含了数据请求,路由的拦截,同时向外界暴露的是一个方法,方法内有三个参数,分别为请求的方式,地址,数据

import axios from 'axios';
import qs from 'qs';
  
const server=axios.create({
    timeout:5000,
    withCredentials:true
 })
 
server.interceptors.request.use((config)=>{
    if(config.method.toUpperCase()=="GET"){
        config.params={...config.data}
    }else if(config.method.toUpperCase()=="POST"){
        config.headers["content-type"] = "appliaction/x-www-form-urlencoded";
        config.data=qs.stringify(config.data);
    }
    vm.handlemount();
    return config;
 },(err)=>{
     Promise.reject(err);
 }) 
 
 server.interceptors.response.use((res)=>{
    if(res.statusText=="OK"){
       vm.handleDestory();
       return res.data
    }
 },(err)=>{
     Promise.reject(err);
})

export default (method,url,data={})=>{
   if(method.toUpperCase()=="GET"){
     return server.get(url,{
        params:data
     })
  }else if(method.toUpperCase()=="POST"){
     return server.post(url,data);
  }
}

可参考博客: https://www.zhihu.com/question/265786082
官网:http://www.axios-js.com/zh-cn/docs/

四、axios调用接口后刷新当前页面或列表

在这里插入图片描述
在这里插入图片描述

五、解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题

const originalPush = VueRouter.prototype.push
   VueRouter.prototype.push = function push(location) {
   return originalPush.call(this, location).catch(err => err)
}
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值