【问题标题】:How to read the current value of a computed property within that computed property method?如何在该计算属性方法中读取计算属性的当前值?
【发布时间】:2020-12-11 09:27:30
【问题描述】:

我们希望在字符串超过 3 个字符时启用查询。启用查询后,它应该保持启用状态。使用 Vue 2 组合 API,我们创建了一个带有查询状态的 reactive 对象:

import { computed, defineComponent, reactive, ref } from '@vue/composition-api'

export default defineComponent({
  setup() {
    const truckId = ref<string>('')
    const driverId = ref<string>('')

    const queryEnabled = reactive({
      driver: false,
      truck: false,
    })

现在将queryEnabled.driver 的值设置为true,当driverId 是一个长度超过3 个字符的字符串时,我们可以这样做:

    const queryEnabled = reactive({
      driver: computed(() => driverId.value.length >= 3),
      truck: false,
    })

这可行,但一旦字符串的字符较少,它也会将queryEnabled.driver设置为false。我们怎样才能拥有一个computed 属性:

  • false 开头
  • 一旦满足条件,将值设置为true
  • 将值保留为 true

这可以在reactive 对象中的一个computed 属性中完成吗?我正在考虑使用function 而不是粗箭头来访问当前computed 属性的this,但无法弄清楚。

【问题讨论】:

  • 你不能在你的情况下使用watcheffectreactive吗?

标签: typescript vue.js vuejs2 vuejs3 vue-composition-api


【解决方案1】:

您无法从自身内部访问computed 属性,因此请使用watch 根据driverId 更新状态:

import { watch, defineComponent, reactive, ref } from '@vue/composition-api'

export default defineComponent({
  setup() {
    const truckId = ref<string>('')
    const driverId = ref<string>('')

    const queryEnabled = reactive({
      driver: false,
      truck: false,
    })

    watch(driverId,(newVal)=>{
      if(!queryEnabled.driver && newVal.length >= 3){
        queryEnabled.driver = true
      }
    })

【讨论】:

  • 这绝对是一个选择。但我希望这可以在单个 computed 属性中实现。
  • computed prop 不被假定为“不可更改”。
  • 我在考虑使用 get 和 set 选项进行计算,但这并没有给出解决方案
  • @DarkLite1 假设我们可以访问自身内部的属性,这可能会造成无限循环,这就像sum=a+b 我们无法访问右侧的总和
猜你喜欢
  • 1970-01-01
  • 2016-12-12
  • 2018-09-19
  • 1970-01-01
  • 2022-08-18
  • 1970-01-01
  • 2022-01-05
  • 2023-03-19
  • 2020-02-05
相关资源
最近更新 更多