vue3 - 05.computed计算属性
vue3 - computed,当数据发生变化的时候,触发computed计算属性。
·
vue3 - computed,当数据发生变化的时候,触发computed计算属性
computed有两种书写方式:
1. 基础用法
例子1:
<template>
<div>
user: <input type="text" v-model="user">
<br />
pwd: <input type="text" v-model="pwd">
<br />
{{info}}
</div>
</template>
<script setup lang='ts'>
import { ref,computed } from 'vue'
const user = ref<string>("")
const pwd = ref<string>("")
const info = computed(() => {
return user.value + "--" + pwd.value
})
</script>
<style scoped>
</style>
例子2:
<template>
<div>
<div v-if="show">显示</div>
<div v-else>隐藏</div>
</div>
</template>
<script setup lang='ts'>
import { ref,computed, onMounted } from 'vue'
const aaa = ref<boolean>()
const bbb = ref<boolean>()
const ccc = ref<boolean>()
onMounted(() => {
aaa.value = true
bbb.value = false
ccc.value = true
})
const show = computed(() => {
return aaa.value && (!bbb.value || ccc.value)
})
</script>
<style scoped>
</style>
例子3:
<template>
<div>
<input type="text" v-model="search" :placeholder="searchVal" />
</div>
</template>
<script setup lang='ts'>
import { ref,computed } from 'vue'
const search = ref<string>()
const searchVal = computed(() => {
return "请输入搜索的商品"
})
</script>
<style scoped>
</style>
2. watch - get / set
<template>
<div>
<input type="text" v-model="search1" />
<input type="text" v-model="search2" />
</div>
</template>
<script setup lang='ts'>
import { ref,computed } from 'vue'
const search1 = ref<string>("")
const search2 = computed({
get(){
return search1.value.split('').reverse().join('')
},
set(newVal){
search1.value = newVal
}
})
</script>
<style scoped>
</style>
computed的set可以写if条件判断,最后通过get返回结果,除了需要做复杂的计算属性之外,一般的都会直接用computed基础用法
更多推荐
已为社区贡献1条内容
所有评论(0)