数据请求axios vs fetch / computed计算属性&watch侦听属性 / mixin全局、局部混入

本文探讨了前端开发中的数据请求,重点比较了axios和fetch两种常见方式。介绍了axios如何封装请求,fetch的直接返回特性,并给出了get和post请求的示例。此外,还讨论了vue中computed、watch和methods的区别,以及mixin的使用场景和优势,强调了在项目中如何选择和应用这些技术。

数据请求

数据请求在前端开发中的使用有两种形式

  1. 使用原生javascript提供的数据请求
  • ajax( 四部曲,一般需要我们结合Promise去封装,使用不是很便利,但是效率很高 )
  • fetch( 本身结合了Promise,并且已经做好了封装,可以直接使用 )
    • 使用格式:
  1. 使用别人封装好的第三方库
    目前最流行的,使用率最高的是 axios

vue中我们最常使用的

  1. vue 1.x 的版本提供了一个封装库 vue-resource , 但是到了vue 2.x版本之后,这个就弃用了
    vue-resource使用方法和 axios 相似度在 95%
    vue-resouce有jsonp方法,但是axios是没有的

  2. vue2.x版本我们最用使用的数据请求是 axios 和 fetch

数据请求的类型

get
post
head
put
delete
option

axios vs fetch

axios得到的结果会进行一层封装,而fetch会直接得到结果

举例:
axios

    {data: 3, status: 200, statusText: "OK", headers: {}, config: {},}
    config: {adapter: ƒ, transformRequest: {}, transformResponse: {}, timeout: 0, xsrfCookieName: "XSRF-TOKEN",}
    data: 3
    headers: {content-type: "text/html; charset=UTF-8"}
    request: XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload,}
    status: 200
    statusText: "OK"
    __proto__: Object

fetch

3 

Axios总结
1.get方法

A: 无参数
    axios.get(url).then(res=>console.log(res).catch(error=>conosle.log(error))
B: 有参数
    axios({
        url: 'http://xxx',
        method: 'get' //默认就是get,这个可以省略,
        params: {
            key: value
        }
    })

2.post
    注意: axios中post请求如果你直接使用npmjs.com官网文档, 会有坑
    解决步骤: 
            1. 先设置请求头 
            2. 实例化 URLSearchParams的构造器函数得到params对象
            3. 使用params对象身上的append方法进行数据的传参

统一设置请求头

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; 
let params = new URLSearchParams()

// params.append(key,value)

params.append('a',1)
params.append('b',2)

单独设置

axios({
    url: 'http://localhost/post.php',
    method: 'post',
    data: params,
    headers: {  //单个请求设置请求头
       'Content-Type': "application/x-www-form-urlencoded"
    }
})
.then(res => {
    console.log( res )
})
.catch( error => {
    if( error ){
    throw error
}
})

Fetch
1.get

fetch('http://localhost/get.php?a=1&b=2')
    .then(res=> res.text()) // 数据格式化 res.json() res.blob()
    .then(data => {
        console.log( data )
    })
    .catch(error => {
        if( error ){
        throw error
    }
})
  • 注意事项:
    A: fetch 的 get 请求的参数是直接连接在url上的, 我们可以使用Node.js提供的url或是qureystring模块来将
    Object --> String
    B: fetch 的请求返回的是Promise对象,所以我们可以使用.then().catch(),但是要记住.then()至少要写两个, 第一个then是用来格式化数据的,第二个then是可以拿到格式化后的数据

  • 格式化处理方式

    fetch('./data.json')
    .then(res=>{
        res.json() //res.text() res.blob()
    })
    .then( data => console.log(data))
    .catch( error => console.log( error ))
    

2.post
fetch文档
https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch#进行_fetch_请求

fetch请求博客
https://blog.youkuaiyun.com/hefeng6500/article/details/81456975

模拟假数据

  1. mock.js
  2. json-server( 启动一个api接口服务器 )

computd vs watch vs methods

computed

  1. computed 计算属性
  • 案例: 为什么vue中要使用计算属性?
    让一个字符反向

  • 分析:

    {{ msg.split('').reverse().join('') }}

    上面代码的写法,有些违背关注点分离,而且会让我们的DOM结构看起来不简洁
  • 解决方案:
    从上面的案例得出两个结论:
    1. 我们的使用结果是要想data选项中定义的数据一样直接使用,那就是最好的
    2. 我们还必须需要一定的逻辑支撑,一想到逻辑,那我们就想到了函数

    综上: vue这边提出来一个新的解决方案就是: 计算属性

    new Vue({
    data: {
      msg: ' my name is yyb '
    },
    computed: {
      //这里存放的是多个方法,这些方法往往都和data选项中的数据有关系
      reverse_msg () {
        return this.msg.split('').reverse().join('')
      }
    }
    }).$mount('#app') // 手动挂载app模板
      
    
  • 在项目中, 使用时候使用计算属性呢?
    只要满足一下两个条件:
    1. 有逻辑处理
    2. 像变量一个使用

    总结: 计算属性一定要有返回值

  1. computed vs methods
    -计算属性是基于它们的依赖进行缓存的。
    -计算属性只有在它的相关依赖发生改变时才会重新求值

watch

watch 侦听属性
1. 是用来监听 data 选项中的数据的,只要data中的数据发生改变,它就会自动触发
2. watch是一个对象,它里面存储的是 { [key: string]: string | Function | Object | Array }
3. 往往watch我们里面常存储的是方法
4. watch中方法的名称就是 data 选项中数据的名称
5. 深度监听

      watch: {
      num: {
        deep: true,
        handler () {
          //数据改变之后执行的事情
        }
      }
    }

对比总结

项目中:

   1. computed:
      - 有逻辑
      - 变量一样使用
   2. methods
      - 事件处理程序
   3. watch
      - 异步操作( 数据请求 )

mixin

使用它的好处:
1. 将 options 中的配置项可以单独抽离出来,单独管理,这样方便维护
使用:

                    new Vue({
                    mixins: [ myMixin ]
                    })
  • 全局混入
    在所有的vm中都会有
    1. 新建一个对象用来保存 options 中某一个配置项,比如: methods
    2. 接下来要将我们创建好的对象混入到我们的 ViewModel 中,我们的混入形式有两种
    - 局部混入 【 推荐 】
    只是在当前 vm 中才有

        Vue.mixin({
        methods: {
            aa () {}
        }
        })
    
import { computed, defineComponent, onMounted, reactive, ref } from "vue"; import { CurdAction, CurdSubAction, CurdCurrentMode } from "@vue-start/pro"; import { pageEnergyEquNodeCal, saveEquMtrl, getEquNodeCalById, deleteEquNodeCal, reportBasicMtrlGetPages, qhGetPage, } from "@/request/srv-energy"; import { useFetch } from "@vue-start/request"; import { ElDialog } from "element-plus"; export default defineComponent(() => { const curdRef = ref(); const state = reactive({ realDepartOptions: [ { label: "是", value: 1 }, { label: "否", value: 2 } ], mtrlTypeOption: [ { label: "生产", value: 1 }, { label: "外购", value: 2 }, { label: "消耗", value: 3 }, { label: "外卖", value: 4 }, ], zzOptions: [], jzOptions: [], // 新增:节点弹框相关状态 nodeModalVisible: false, // 弹框显示状态 currentRecord: null // 当前点击的记录 }); const curdState = reactive({ mode: CurdCurrentMode.LIST, detailData: { equName: "", equCode: "", mtrlName: "", mtrlTypeName: "", mtrlUnit: "", mtrlTypeId: "", factor: "", summaryType: "", calRule: "", nodes: "" }, }); // 新增:打开节点弹框 const openNodeModal = (record) => { console.log("打开节点弹框,当前记录:", record); state.currentRecord = record; // 保存当前记录 state.nodeModalVisible = true; // 显示弹框 }; // 新增:关闭节点弹框 const closeNodeModal = () => { state.nodeModalVisible = false; // 隐藏弹框 state.currentRecord = null; // 清空当前记录 }; // 定义所有列配置 const allColumns = [ { title: "装置名称", dataIndex: "equName", valueType: "select", formItemProps: { required: true }, search: true, formFieldProps: { options: state.zzOptions, labelField: "label", valueField: "value", onChange: (value) => { const selected = state.zzOptions.find(option => option.value === value); if (selected) { curdState.detailData.equName = selected.label; curdState.detailData.equCode = selected.value; } } }, alwaysShow: true }, { title: "介质名称", dataIndex: "mtrlName", valueType: "select", formItemProps: { required: true }, search: true, formFieldProps: { options: state.jzOptions, labelField: "label", valueField: "value", onChange: (value) => { const selected = state.jzOptions.find(option => option.value === value); if (selected) { curdState.detailData.mtrlName = selected.label; curdState.detailData.mtrlCode = selected.value; } } }, alwaysShow: true }, { title: "介质类型", dataIndex: "mtrlTypeName", valueType: "select", formItemProps: { required: true }, search: true, formFieldProps: { options: state.mtrlTypeOption, labelField: "label", valueField: "value", onChange: (value) => { const selected = state.mtrlTypeOption.find(option => option.value === value); if (selected) { curdState.detailData.mtrlTypeName = selected.label; curdState.detailData.mtrlTypeId = selected.value; } } }, alwaysShow: true }, { title: "计量单位", dataIndex: "mtrlUnit", formItemProps: { required: true }, search: false, alwaysShow: true }, { title: "计算规则", dataIndex: "summaryType", formItemProps: { required: false }, search: false, showInEditAdd: false }, { title: "计算表达式", dataIndex: "calRule", formItemProps: { required: false }, search: false, showInEditAdd: false }, { title: "节点信息", dataIndex: "nodesDisplay", formItemProps: { required: false }, search: false, showInEditAdd: false, customRender: ({ record }) => { // 点击事件绑定openNodeModal if (Array.isArray(record.nodes) && record.nodes.length === 0) { return <span style="color: #1890ff; cursor: pointer;" onClick={() => openNodeModal(record)}>添加节点</span>; } if (Array.isArray(record.nodes) && record.nodes.length > 0) { return <span style="color: #1890ff; cursor: pointer;" onClick={() => openNodeModal(record)}>{record.nodes.map(node => node.nodeName).join(",")}</span>; } return <span style="color: #1890ff; cursor: pointer;" onClick={() => openNodeModal(record)}>-</span>; } }, { title: "系数", dataIndex: "factor", formItemProps: { required: false }, search: false, showInEditAdd: false }, ]; const columns = computed(() => { const isEditOrAdd = [CurdCurrentMode.EDIT, CurdCurrentMode.ADD].includes(curdState.mode); return allColumns.filter(column => { if (column.alwaysShow) return true; if (column.showInEditAdd !== undefined) { return isEditOrAdd ? column.showInEditAdd : true; } return true; }); }); const searchModel = reactive({}); const operates = [ { action: CurdAction.LIST, actor: pageEnergyEquNodeCal, convertParams: (params) => { const { mtrlTypeName, ...restParams } = params; return { body: { ...restParams, ...(mtrlTypeName !== undefined && { mtrlTypeId: mtrlTypeName }), pageSize: params.pageSize, pageNum: params.page, }, }; }, onSuccess: (response) => { // 原有逻辑保持不变 const data = response.res?.data?.data; if (data?.records && Array.isArray(data.records)) { data.records = data.records.map(item => { if (Array.isArray(item.nodes)) { item.nodesDisplay = item.nodes.map(node => node.nodeName).join(","); } else { item.nodesDisplay = "-"; } return item; }); } return data; } }, { action: CurdAction.ADD, actor: saveEquMtrl, onClick: () => { curdState.mode = CurdCurrentMode.ADD; curdState.detailData = {}; }, label: "新增", show: true, convertParams: (params) => { return { body: { ...params, ...curdState.detailData, }, }; }, }, { action: CurdAction.EDIT, actor: saveEquMtrl, show: true, convertParams: (params) => { return { body: { ...params, ...curdState.detailData, }, }; }, }, { action: CurdAction.DETAIL, actor: getEquNodeCalById, convertParams: (params) => { return { id: params.cId, }; }, show: false, }, { action: CurdAction.DELETE, actor: deleteEquNodeCal, convertParams: (params) => { return { cId: params.cId, }; }, }, ]; const listProps = { searchProps: { model: searchModel, }, tableProps: { serialNumber: true, operate: { column: { width: 300, }, }, }, }; const handleFinish = (values) => { if (curdState.mode === CurdCurrentMode.EDIT) { curdRef.value.sendCurdEvent({ action: CurdAction.EDIT, type: CurdSubAction.EXECUTE, values }); } else { curdRef.value.sendCurdEvent({ action: CurdAction.ADD, type: CurdSubAction.EXECUTE, values }); } }; // const { request: fetchJztList } = useFetch(reportBasicMtrlGetPages, { // onSuccess: (response) => { // const data = response.res?.data?.data.records; // if (Array.isArray(data) && data.length > 0) { // state.jzOptions = data.map(item => ({ // label: item.mtrlName, // value: item.mtrlCode // })); // } // }, // onError: (error) => { // console.error("获取介质列表失败:", error); // } // }); const { request: fetchZztList } = useFetch(qhGetPage, { onSuccess: (response) => { const data = response.res?.data?.data?.records || []; console.log("装置列表数据:", data); if (Array.isArray(data) && data.length > 0) { state.zzOptions = data.map(item => ({ label: item.equName, value: item.equCode })); console.log(state.zzOptions,'state.zzOptions') } else { state.zzOptions = []; } }, onError: (error) => { console.error("获取装置列表失败:", error); } }); onMounted(() => { fetchZztList({ body: { pageSize: 100, pageNum: 1 } }); // fetchJztList({ // body: { pageSize: 100, pageNum: 1 } // }); }); return () => { return ( <pro-page> <pro-modal-curd ref={curdRef} columns={columns.value} operates={operates} listProps={listProps} curdState={curdState} formProps={{ labelWidth: "120px", onFinish: handleFinish, }} modalProps={{ width: 800 }} > <pro-curd-list-connect /> <pro-curd-modal-form-connect /> </pro-modal-curd> {/* 仅调起空弹框 */} <ElDialog title="节点信息" // 弹框标题(可自定义) visible={state.nodeModalVisible} // 绑定显示状态 onClose={closeNodeModal} // 关闭时触发的方法 width="500px" // 弹框宽度(可按需调整) > {/* 弹框内部留空(无需内容) */} </ElDialog> </pro-page> ); }; }); { "code": 0, "msg": null, "data": { "records": [ { "equCode": "Z4QZ2111", "equName": "常减压蒸馏装置 ", "equType": 1, "equReal": 1, "departCode": "1001", "processLine": null, "equStatus": 1, "createDate": "2013-07-04 10:15:21" }, { "equCode": "Z4QZ2112", "equName": "轻烃回收装置 ", "equType": 1, "equReal": 1, "departCode": "1001", "processLine": null, "equStatus": 1, "createDate": "2013-07-04 10:15:21" }, { "equCode": "Z4QZ2411", "equName": "催化裂化装置 ", "equType": 1, "equReal": 1, "departCode": "1001", "processLine": null, "equStatus": 1, "createDate": "2013-07-04 10:15:00" }, { "equCode": "Z4QZ2611", "equName": "延迟焦化装置 ", "equType": 1, "equReal": 1, "departCode": "1001", "processLine": null, "equStatus": 1, "createDate": "2013-07-04 10:15:21" }, { "equCode": "Z4QZ2414", "equName": "汽油加氢装置 ", "equType": 1, "equReal": 1, "departCode": "1001", "processLine": null, "equStatus": 1, "createDate": "2013-07-04 10:15:21" }, { "equCode": "Z4QZ2413", "equName": "产品精制装置 ", "equType": 1, "equReal": 1, "departCode": "1001", "processLine": null, "equStatus": 1, "createDate": "2013-07-04 10:15:00" }, { "equCode": "Z4QZ2211", "equName": "重整预加氢装置 ", "equType": 1, "equReal": 1, "departCode": "", "processLine": null, "equStatus": 1, "createDate": "2013-07-04 10:15:21" }, { "equCode": "Z5QZ2211", "equName": "连续重整装置 ", "equType": 1, "equReal": 1, "departCode": "1002", "processLine": null, "equStatus": 1, "createDate": "2013-07-04 10:15:21" }, { "equCode": "Z5QZ2212", "equName": "芳烃抽提装置 ", "equType": 2, "equReal": 1, "departCode": "1002", "processLine": null, "equStatus": 1, "createDate": "2013-07-04 10:15:21" }, { "equCode": "Z4QZ2311", "equName": "煤油加氢装置 ", "equType": 1, "equReal": 1, "departCode": "1002", "processLine": null, "equStatus": 1, "createDate": "2013-07-04 10:15:00" } ], "total": 61, "size": 10, "current": 1, "pages": 7 }, "ok": true } 装置名称下拉列表没有数据 不改变原代码 对代码优化解决一下
08-29
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值