原创 

vue3.0 TypeScript 导入axios和this 的使用

分类:前端    550人阅读    IT小君  2021-05-23 16:21

吐槽:

对于使用者来说我还是喜欢弱类型,js这么简单的东西干嘛搞个强类型,天下乌鸦一样黑了  


1、this的使用

vue3 中直接使用this 会报错,可以通过VUE 提供的getCurrentInstance() 方法获取当前app对象

代码示例:

export default defineComponent({
  name: 'editor',
  components: {
    ...
  },
  setup() {
    const { ctx } = (getCurrentInstance() as any);
    const onCheck = (checkedKeys: Record<any, any>)=>{
      ctx.checkedKeys = checkedKeys;
    }
    
    return {
     onCheck
    }
  },
})

醒悟:vue3使用的是Typescript,使用类的方式操作属性,所以其实修改类变量就好,不需要使用this,vue2.0过度行为


2、axios 的导入

vue3 中由于使用ts无法将axios直接挂到vue属性上,通过扩展全局自定义属性接口可以像vue2一样使用

main.ts代码示例:

import {AxiosInstance } from "axios";
import Axios from "axios";

//全局配置Axios
declare module '@vue/runtime-core' {
    interface ComponentCustomProperties {
      $axios: AxiosInstance;
    }
}
app.config.globalProperties.$axios=Axios;  //this.Axios

使用:

ctx.$axios.post('/admgr/infoProgramGroup/list.json')
      .then(function (response: any) {
        console.log(response);
        const random = Math.random().toString(36).substring(2, 6);
        response.data.data.forEach((element: any) => {
          treeData1.value.push({
          id: element.pgroupId,
          pId: element.parentId,
          value: random,
          title: element.groupName,
          });
        });
        
      })
      .catch(function (error: any) {
        console.log(error);
      });



以上都是延续vue2 的使用风格




点击广告,支持我们为你提供更好的服务

HTML5 Canvas竖直流动线条背景动画特效

HTML5现代家居装潢公司网站模板

html5 svg夜空中星星流星动画场景特效

css鼠标跟随文字模糊特效

响应式太阳能能源公司网站模板

html5 canvas彩色碎片组合球形旋转动画特效

html5图标下拉搜索框自动匹配代码

小众时尚单品在线电子商务网站模板

中小型创意设计服务公司网站模板

响应式咖啡饮品宣传网站模板

网页设计开发公司网站模板

canvas炫酷鼠标移动文字粒子特效

html5 canvas进度条圆环图表统计动画特效

jQuery右端悬浮带返回顶部特效

css+js实现的颜色渐变数字时钟动画特效

响应式时尚单品在线商城网站模板

js+css3抽奖转盘旋转点餐代码

HTML5数字产品服务公司网站模板

现代时尚家具公司网站模板

有机水果蔬菜HTML5网站模板

点击广告,支持我们为你提供更好的服务
 工具推荐 更多»
点击广告,支持我们为你提供更好的服务