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;
};

界面

posted @   南无、  阅读(4189)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示