vue3-render-fetch封装

1. 前言

render函数其实之前工作中用的非常多,因为之前有部分项目是很多列表需要编辑,修改,等操作,都需要自己布局 ,所以用的render比较多
v3render做了简化,,写起来更方便了


2. render

1.字符串模板的另一种选择,允许你充分利用 JavaScript的编程功能。
2.render函数的优先级于从挂载元素 template 选项或内置 DOM 提取出的 HTML 模板编译渲染函数。


2.1 简要代码

组件使用

 app.component('my-title', {
  render() {
    return Vue.h(
      'h1',           // 标签名称
      this.blogTitle  // 标签内容
    )
  },
  props: {
    blogTitle: {
      type: String,
      required: true
    }
  }
})

2.2 单文件组件使用

import {reactive,h,toRefs} from "vue";
export default {
    setup () {
        const  state =   reactive({
            count:1
        })
        return {...toRefs(state)}
    },
      //可以把 template注释掉
  render(){
    return h("div",{title:"渲染函数",yzs:"自定义属性也可以"},this.count)
  }
}

2.3 分析

1.h函数因为源码底层这个函数就叫h
2.第二个参数是属性对象,属于可选的,不写也行,属性也可以自定义
3.第三个参数就是标签内容
4.render函数和setup是同级的


2.4 嵌套

render(){
    return h("div",{title:"渲染函数"},[h("h1",{title:"标题"},"是是")])
  }

这个嵌套可以一直进行下去,当然一般也不会嵌套几层,结构太乱了


3. fetch 基础封装

src/config/indexjs

3.1 简要代码

export default async(url = '', data = {}, type = 'GET', method = 'fetch') => {
    const baseUrl = "https://xx.yzs.org"
    type = type.toUpperCase();
    url = baseUrl + url;

    if (type == 'GET') {
        let dataStr = ''; //数据拼接字符串
        Object.keys(data).forEach(key => {
            dataStr += key + '=' + data[key] + '&';
        })

        if (dataStr !== '') {
            dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
            url = url + '?' + dataStr;
        }
    }

    if (window.fetch && method == 'fetch') {
        let requestConfig = {
            credentials: 'include',
            method: type,
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            mode: "cors",
            cache: "force-cache"
        }

        if (type == 'POST') {
            Object.defineProperty(requestConfig, 'body', {
                value: JSON.stringify(data)
            })
        }
        
        try {
            const response = await fetch(url, requestConfig);
            const responseJson = await response.json();
            return responseJson
        } catch (error) {
            throw new Error(error)
        }
    } else {
        return new Promise((resolve, reject) => {
            let requestObj;
            if (window.XMLHttpRequest) {
                requestObj = new XMLHttpRequest();
            } else {
                requestObj = new ActiveXObject;
            }

            let sendData = '';
            if (type == 'POST') {
                sendData = JSON.stringify(data);
            }

            requestObj.open(type, url, true);
            requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            requestObj.send(sendData);

            requestObj.onreadystatechange = () => {
                if (requestObj.readyState == 4) {
                    if (requestObj.status == 200) {
                        let obj = requestObj.response
                        if (typeof obj !== 'object') {
                            obj = JSON.parse(obj);
                        }
                        resolve(obj)
                    } else {
                        reject(requestObj)
                    }
                }
            }
        })
    }
}

4. fecth 接口封装

src/api/login.js

4.1 登录接口封装

import fetch from "@/config"
/**
 * 账号密码登录
 */
export const accountLogin = (username, password, captcha_code) => fetch('/v2/login', {username, password, captcha_code}, 'POST');

4.2 列表封装

export const getList= () => fetch('/v1/list', {
    type: 1
});

5. 接口使用

5.1 引入

import { reactive, toRefs ,onMounted} from 'vue'
import {cityGuess, getList} from '@/api/getData'

5.2 setup核心

export default {
    setup () {
        const state = reactive({
            count: 0,
            name:""
        })
        onMounted(() => {
             //列表
            getList().then(res => {
                    console.log("REs-----------:",res)
                    state.name = res.name
            })
            accountLogin("用户名","密码","验证码").then(res => {
                    console.log("REs-----------:",res)
            }).catch(err=>{
                console.log("err:",err)
            })
        })
        return {
            ...toRefs(state),
        }
    }
}

6. 模板

<template>
    <div>
        <h1> 登录 fetch</h1>
        <h1>{{name}}</h1>
    </div>
</template>

参考资料


初心

我所有的文章都只是基于入门,初步的了解;是自己的知识体系梳理;
如果能帮助到有缘人,非常的荣幸,一切为了部落的崛起;
共勉
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本文目录 1.简述Vue的响应式原理 2.delete和Vue.delete删除数组的区别 3.v-for循环时为...
    前端辉羽阅读 4,513评论 0 12
  • 1.v-if 和v-show区别 v-if 真正条件渲染 DOM切换 销毁 重建,不停的销毁和创建比较消耗性能。v...
    抽疯的稻草绳阅读 5,089评论 0 22
  • Vue3.0的优势 性能比Vue2.x快1.2~2倍 按需编译,体积比Vue2.x更小 组合API(类似React...
    强某某阅读 5,442评论 0 5
  • 前言 Vue基本用法很容易上手,但是有很多优化的写法你就不一定知道了,本文从列举了 36 个 vue 开发技巧; ...
    阿_军阅读 5,312评论 0 1
  • 16宿命:用概率思维提高你的胜算 以前的我是风险厌恶者,不喜欢去冒险,但是人生放弃了冒险,也就放弃了无数的可能。 ...
    yichen大刀阅读 11,285评论 0 4