如何在计算 属性 方法中读取计算 属性 的当前值?
How to read the current value of a computed property within that computed property method?
我们希望在字符串超过 3 个字符时启用查询。启用查询后,它应该保持启用状态。使用 Vue 2 Composition 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,
})
当 driverId
是长度超过 3 个字符的字符串时,现在将 queryEnabled.driver
的值设置为 true
,我们可以这样做:
const queryEnabled = reactive({
driver: computed(() => driverId.value.length >= 3),
truck: false,
})
这有效,但一旦字符串字符较少,它也会将 queryEnabled.driver
设置为 false
。我们怎样才能有一个 computed
属性 那:
- 以
false
开头
- 满足条件后将值设置为
true
- 将值保持为
true
之前设置并且不会更改回来
是否可以仅在 reactive
对象中的一个 computed
属性 内完成?我正在考虑使用 function
而不是粗箭头来访问当前 computed
属性 的 this
但无法弄清楚。
您无法从内部访问 computed
属性,因此请使用 watch
根据 driverId
:[=14= 更新状态]
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
}
})
我们希望在字符串超过 3 个字符时启用查询。启用查询后,它应该保持启用状态。使用 Vue 2 Composition 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,
})
当 driverId
是长度超过 3 个字符的字符串时,现在将 queryEnabled.driver
的值设置为 true
,我们可以这样做:
const queryEnabled = reactive({
driver: computed(() => driverId.value.length >= 3),
truck: false,
})
这有效,但一旦字符串字符较少,它也会将 queryEnabled.driver
设置为 false
。我们怎样才能有一个 computed
属性 那:
- 以
false
开头
- 满足条件后将值设置为
true
- 将值保持为
true
之前设置并且不会更改回来
是否可以仅在 reactive
对象中的一个 computed
属性 内完成?我正在考虑使用 function
而不是粗箭头来访问当前 computed
属性 的 this
但无法弄清楚。
您无法从内部访问 computed
属性,因此请使用 watch
根据 driverId
:[=14= 更新状态]
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
}
})