vue3 使用computed计算属性
demo1: 简单使用computed
<template>
<div :style="{'width': width}" style=" height: 100px;background: #0a0"></div>
</template>
<script lang="ts" setup>
import {ref, reactive, computed} from 'vue'
const width = computed(()=> {
return `${Math.abs(300 -100)}px`; //300和100可替换成想要动态计算的数值
})
</script>
demo2: 使用computed的get和set方法
<template>
<p style="margin: 10px 0;"><el-input type="text" v-model="currentData"></el-input></p>
<p style="margin: 10px 0;"><el-input type="text" v-model="nextData"></el-input></p>
</template>
<script lang="ts" setup>
import {ref, reactive, computed} from 'vue'
const currentData = ref(18)
const nextData = computed({
get() {
return currentData.value + 1
},
set(value) {
console.log(value) // 输出新修改的值
return currentData.value = value - 1
}
})
</script>
|