asyncComputed 异步计算属性

2023-05-16

asyncComputed 异步计算属性

我们项目中最近使用了异步计算属性,个人感觉很好用,特此推荐给大家。

一、案例

假设这样一个场景:

一个列表数据 data 是通过接口返回,请求参数中有一个 id 的数据,这个 id 数据变化的话,需要重新请求接口获取数据。

按照普通方法来的话,需要按以下步骤实现。

  1. data 中定义一个 list 数据
  2. 需要在 methods 中定义一个 request 方法,请求接口赋值 list
  3. 在页面创建时调用 request 方法,获得首次数据
  4. 通过 watch 监听 id 数据,在变化时调用 request 方法(更新 list 数据)

使用异步计算属性的话,只需要以下代码:

  asyncComputed: {
    list () {
      return Vue.http.get('/get-list-by-id/' + this.id)
        .then(response => response.data)
    }
  }

接下来,详细介绍一下异步计算属性。

二、安装与使用

npm install --save vue-async-computed

当使用了 webpack 或者 browserify 等时,需要明确通过 Vue.use 实现安装。

import Vue from 'vue'
import AsyncComputed from 'vue-async-computed'

Vue.use(AsyncComputed)

和同步计算属性类似,异步计算属性有 get 方法,但是没有 set 方法,设置了也会被忽略。

  asyncComputed: {
    blogPostContent: {
      get () {
        return Vue.http.get('/post/' + this.postId)
          .then(response => response.data.postContent)
       }
    }
  }

三、默认值

异步计算属性还可以设置默认值。在首次加载数据之前使用。

  asyncComputed: {
    blogPostContent: {
      get () {
        return Vue.http.get('/post/' + this.postId)
          .then(response => response.data.postContent)
       },
       default: 'Loading...'
       // default 也可以使用函数,设置基于其他数据的默认值
       default () {
        return 'Loading post ' + this.postId
      }
    }
  }

默认值还可以全局设置。

Vue.use(AsyncComputed, {
  default: 'Global default value'
})

四、重新计算

有时候,异步计算属性的依赖项没有变化,但是需要重新计算。

当某个数据变化时的重新计算可以这么写。

new Vue({
  data: {
    postId: 1,
    timesPostHasBeenUpdated: 0
  },
  asyncComputed: {
    blogPostContent: {
      get () {
        return Vue.http.get('/post/' + this.postId)
          .then(response => response.data.postContent)
      },
      // timesPostHasBeenUpdated 变化时重新计算
      watch: ['timesPostHasBeenUpdated']
    }
  }
}

还可以通过点语法监听具体属性值。
watch: [‘a.b.c’, ‘d.e’] 可以监听 this.a.b.c 和 this.d.e.

另外还可以在某些情况下手动触发重新计算。

  asyncComputed: {
    blogPosts: {
      get () {
        return Vue.http.get('/posts')
          .then(response => response.data)
      },
    }
  },
  methods: {
    refresh() {
      // 手动触发
      this.$asyncComputed.blogPosts.update();
    }
  }

五、有条件的重新计算

使用 watch 会重新计算,但是不会考虑监听属性的值得具体情况。

这个时候可以使用 shouldUpdate 实现具体条件下的重新计算。

  asyncComputed: {
    blogPostContent: {
      get () {
        return Vue.http.get('/post/' + this.postId)
          .then(response => response.data.postContent)
      },
      // pageType 或者 postId 改变都会重新计算,但必须同时满足下面条件
      shouldUpdate () {
        return this.pageType !== 'index'
      }
    }
  }

六、lazy 属性

有时候不希望异步计算属性一直重新计算,可以使用 lazy:true 实现只在首次访问时计算。

  asyncComputed: {
    mightNotBeNeeded: {
      // mightNotBeNeeded 的值只会在首次计算
      lazy: true,
      get () {
        return Vue.http.get('/might-not-be-needed/' + this.id)
          .then(response => response.data.value)
      }
    }
  }

七、计算状态

每个异步计算属性,都会向 $asyncComputed 中添加一个对象(包含有关该对象当前计算状态的信息)。

该对象包含以下属性:

{
  // 之一:updating, success, error
  state: 'updating',
  // 布尔值,属性更新时为true
  updating: true,
  // 没有错误发生且当前值可用时,该属性不再更新
  success: false,
  // promise 出现 rejected
  error: false,
  // promise 出现 rejected 时的原始错误信息
  exception: null
}

用于展示更新/错误信息。

  asyncComputed: {
    posts() {
      return Vue.http.get('/posts')
        .then(response => response.data)
      }
    }
  }
  
// 每次 posts 数据更新时,以下信息都会展示
// <div v-if="$asyncComputed.posts.updating"> (Re)loading posts </div>

八、全局错误处理

默认情况下,在异步计算属性中发生 promise 的 reject 的情况下,vue-async-computed 将为你记录错误。

如果你想使用自定义日志记录函数,那么插件将接受 errorHandler 选项,该选项应该是你希望使用错误信息调用的函数。

默认情况下,它将仅以错误的堆栈跟踪作为参数进行调用,但是如果将 errorHandler 与 useRawError 设置为 true,函数将接收原始错误,即抛出错误的Vue实例的引用和错误的堆栈跟踪。

Vue.use(AsyncComputed, {
  errorHandler (stack) {
    console.log('Hey, an error!')
    console.log('---')
    console.log(stack)
  }
)

// useRawError
Vue.use(AsyncComputed, {
  useRawError: true,
  errorHandler (err, vm, stack) {
    console.log('An error occurred!')
    console.log('The error message was: ' + err.msg)
    console.log('And the stack trace was:')
    console.log(stack)
  }
)

git 地址:vue-async-computed

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

asyncComputed 异步计算属性 的相关文章

  • 【工作感悟】99%即是不成功

    今晚由于修改代码导致cpu使用率爆满 xff0c 然后疯狂地 kill 9 xxxx 事后究其原因 xff0c 还是我没有考虑完善 xff0c 很多事情都是考虑到眼前一段时间 xff0c 而非一个月之后怎么样 xff0c 一年之后怎么样 反
  • centos 自带python 2.6 链接mysql 报错

    mysql python安装时EnvironmentError mysql config not found error command 39 gcc 39 failed with exit status 1 参考 https www cn
  • Spring Boot自定义log4j2日志文件 按天记录

    转载 https www cnblogs com advancing p 7922463 html Spring Boot自定义log4j2日志文件 背景 xff1a 因为从 Spring Boot 1 4开始的版本就要用log4j2 了
  • datax fieldDelimiter ’\001’ fieldDelimiter": “\u0001”!!!

    原文 xff1a https blog csdn net Angular need article details 84000592 作者 xff1a Angular need 来源 xff1a CSDN 2 datax把数据从Mysql导
  • GPG key retrieval failed: [Errno 14] Could not open/read file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6

    运维给分配了一个新的服务器 xff0c 发现服务器上并没有安装mysql xff0c 一些shell脚本调用的mysql命令就无法使用 xff0c 随后开始安装mysql xff0c 本来准备请运维帮忙安装 xff0c 但是运维说自己装吧
  • golang go get中断问题解决: git 推送出现 "fatal: The remote end hung up unexpectedly" 解决方案

    转自 https blog csdn net weixin 38450840 article details 80701173 git 推送出现 fatal The remote end hung up unexpectedly 解决方案
  • Maven 镜像源配置

    settings xml 文件 lt xml version 61 34 1 0 34 encoding 61 34 UTF 8 34 gt lt settings xmlns 61 34 http maven apache org SET
  • 前端免费模板

    最近发现了一个前端免费模板 xff0c 分享给大家 xff1a http www mobanwang com mb
  • Postman 使用教程

    关注 开源Linux xff0c 选择 设为星标 回复 学习 xff0c 有我为您特别筛选的学习资料 postman是一款支持http协议的接口调试与测试工具 xff0c 其主要特点就是功能强大 xff0c 使用简单且易用性好 无论是开发人
  • 3.卡尔曼滤波理论基础之最优估计(最小方差估计)

    文章目录 一 最小方差估计例子 二 线性最小方差估计三 其他最优估计1 极大验后估计2 极大似然估计 四 总结 一 最小方差估计 前两篇文章对最优估计中的最小二乘估计进行了较为系统的介绍 我们已经知道 xff0c 所谓最优估计就是让估值结果
  • YOLOV4与YOLOV3的区别

    YOLOV4与YOLOV3的区别 A big bliss的博客 CSDN博客 yolov3和yolov4的区别 首先 xff0c 先大概的说下二者之间的差别 xff1a 1 特征提取网络的不同 2 激活函数的不同 3 loss的不同 4 数
  • HTTP Authorization

    HTTP Authorization 授权流程 在项目中往往需要对访问的请求进行安全认证 xff0c 只有认证通过的请求 xff0c 才能进行相关的操作 开发者需要颁发 AccessKey 和 SecretKey 给用户 xff0c 用户如
  • 求助!!tensorflow无法调用GPU计算。。

    求助 xff01 xff01 tensorflow无法调用GPU计算 如题 xff0c 本人是小白级别的爱好者 xff0c 使用的是联想台式机 xff0c win10系统 xff0c 有一块GeForce GT730的独立显卡 xff0c
  • C++系列: 嵌套命名空间

    目录 1 什么是嵌套命名空间 xff1f 2 实验 2 1 外部引用嵌套命名空间内的符号 2 2 命名空间内容不同层次间符号的引用 3 最后 1 什么是嵌套命名空间 xff1f 嵌套命名空间就是在命名空间里面在定义其它的命名空间 xff0c
  • 树莓派:ssh“疯掉”了

    昨晚 xff0c 电脑用ssh连接不了树莓派 我非常淡定 xff0c 首先在树莓派上打开配置 xff0c 看看ssh有没有打开 xff0c 很明显 xff0c 一直开着的 嗯 xff0c 可能无线连接的分配的ip地址变了 于是 xff0c
  • 串口通信协议

    1 串口通信协议简介 串口通信 xff08 serial communication xff09 是一种设备间非常常用的串行通信方式 xff0c 大部分电子设备都支持 xff0c 电子工程师再调试设备时也经常使用该通信方式输出调试信息 2
  • vim 实现批量注释

    vim 实现批量注释 第一种方法 批量插入字符快捷键 xff1a Ctrl 43 v进入VISUAL BLOCK xff08 可视块 xff09 模式 xff0c 按 j xff08 向下选取列 xff09 或者 k xff08 向上选取列
  • CMake下头文件和链接库的使用

    一 头文件与链接库文件的区别 头文件 xff1a 申明函数接口 库文件 xff1a 存放函数的定义 库文件通过头文件向外导出接口 xff0c 用户通过头文件找到库文件中需要的函数实现代码进行链接至程序当中 二 静态链接库 xff08 lib
  • 查看虚拟机里的Centos7的IP

    这里之所以是查看下IP xff0c 是我们后面要建一个Centos远程工具Xshell 连接Centos的时候 xff0c 需要IP地址 xff0c 所以我们这里先 学会查看虚拟机里的Centos7的IP地址 首先我们登录操作系统 用户名r
  • 堡垒机-百百堡垒机-基于WEB的VNC、RDP、SSH远程控制。无须任何插件,随时随地远程。

    1 百百堡垒机 基于web的软件堡垒机 xff0c 无任何插件 随时随地运维就是这么简单 百百堡垒机是开源软件 git https gitee com baibaiclouds platform 官网地址 http bb app yun c

随机推荐