使用方法,computed,watch,watchEffect完成加减乘除

<template>
    <h1>方法</h1>
    <input type="text" v-model="input3" @input="meth()">
    +
    <input type="text" v-model="input4" @input="meth()">
    =
    <input type="text" v-model="sum">

    <h1>computed</h1>
    <input type="text" v-model="input1">
    -
    <input type="text" v-model="input2">
    =
    <input type="text" v-model="reduce">

    <h1>watch</h1>
    <input type="text" v-model="input5">
    *
    <input type="text" v-model="input6">
    =
    <input type="text" v-model="ride">

    <h1>watchEffect</h1>
    <input type="text" v-model="input7">
    ÷
    <input type="text" v-model="input8">
    =
    <input type="text" v-model="except">
</template>
<script lang="ts" >
import { defineComponent, computed, ref, watch, toRef, watchEffect } from "vue";

export default defineComponent({
    setup() {
        let input1 = ref("");
        let input2 = ref("");

        let input3 = ref("")
        let input4 = ref("")
        let sum = ref()

        let input5 = ref("")
        let input6 = ref("")
        let ride = ref()

        let input7 = ref("")
        let input8 = ref("")
        let except = ref()

        function meth() {
            if (input3.value != "" && input4.value != "") {
                return sum.value = parseInt(input3.value) + parseInt(input4.value);
            }
        }
        let reduce = computed(() => {
            if (input1.value == "" || input2.value == "") {
                return ""
            } else {
                return parseInt(input1.value) - parseInt(input2.value)
            }
        })
        watch([input5, input6], (newValue, oldValue) => {
            if (newValue[0] != "" && newValue[1] != "") {
                console.log("触发了")
                return ride.value = (parseInt(newValue[0]) * parseInt(newValue[1]))
            }
            ride.value = ""
        })
        watchEffect(() => {
            input7.value;
            input8.value;
            if (input7.value != "" && input8.value != "") {
                return except.value = (parseInt(input7.value) / parseInt(input8.value));
            }
            except.value = ""
        })
        return { input1, input2, reduce, meth, input3, input4, sum, input5, input6, ride, input7, input8, except }
    }
})
</script>
  
  
  

 

posted on 2022-11-01 09:52  最帅爸爸  阅读(58)  评论(0)    收藏  举报