vue3+ts使用computed
说明
计算属性主要使用来描述依赖响应式状态的复杂逻辑,即对多个变量或者对象进行处理后返回一个结果值
注意
计算属性的返回值应该被视为只读的,并且永远不应该被更改,如果想要更新应该更新它所依赖的源状态以触发新的计算。
应用场景
计算商品总价 | 半选框 | 按钮是否禁用 | 更多or收起......
举例
- 计算商品总价
template
<el-form :label-width="120"> <el-form-item label="Unit Price"> <el-input v-model="unitPrice" type="number"></el-input> </el-form-item> <el-form-item label="Quantity"> <el-input v-model="quantity" type="number"></el-input> </el-form-item> <el-form-item label="Total Price"> <el-input v-model="totalPrice" disabled></el-input> </el-form-item> </el-form>
script
import { computed, ref } from 'vue';
let quantity = ref<number | undefined>();
let unitPrice = ref<number | undefined>();
let totalPrice = computed({
get() {
if (unitPrice.value && quantity.value) {
return unitPrice.value * quantity.value;
}
},
set() {}
});
界面

- 半选框+按钮是否禁用
template
<el-row> <el-col :span="20"> <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">Check all</el-checkbox> </el-col> <el-col :span="4"> <el-button @click="handlePrint" type="primary" :disabled="canPrint">多选打印</el-button> </el-col> <el-col :span="24"> <el-checkbox-group v-model="checkedList" @change="handleCheckedChange"> <el-checkbox v-for="city in chooseList" :key="city" :label="city">{{ city }}</el-checkbox> </el-checkbox-group> </el-col> </el-row>
script
let checkAll = ref(false); const chooseList = ['html', 'css', 'javascript', 'vue', 'react', 'angular', 'uniapp']; let checkedList = ref<string[]>([]); let isIndeterminate = computed({ get() { return checkedList.value.length > 0 && checkedList.value.length < chooseList.length; }, set(val) {} }); const handleCheckAllChange = (val: boolean) => { checkedList.value = val ? chooseList : []; }; const handleCheckedChange = (val: string[]) => { checkAll.value = val.length === chooseList.length; }; let canPrint = computed(() => { return checkedList.value.length < 2; }); const handlePrint = () => { console.log('handlePrint', checkedList.value); };
界面
- 按钮文字
template
<el-row> <el-col :span="20">活着</el-col> <el-col :span="4"> <el-button @click="changeShow">{{ btnTxt }}</el-button> </el-col> <el-col v-if="isShow" class="paragraph">最初我们来到这个世界,是因为不得不来;最终我们离开这个世界,是因为不得不走。</el-col> </el-row>
script
let isShow = ref(false); let btnTxt = computed(() => { return isShow.value ? '收起' : '更多'; }); const changeShow = () => { isShow.value = !isShow.value; };
界面



浙公网安备 33010602011771号