vue2,vue3同时监听多个数据变化

我是使用vue计算属性(computed)将需要监听的数据拼接在一起,再通过watch进行监听

1.vue普通写法

<template>
    <div id="app">
        <el-input v-model.number="value1" />
        <el-input v-model.number="value2" />
        <el-input v-model.number="object1.value3" />
        <el-date-picker v-model="object1.value4" type="date" value-format="yyyy-MM-DD" />
    </div>
</template>
<script>
    export default {
        name: 'app',
        data() {
            return {
                value1: 0,
                value2: 0,
                object1: {
                    value3: 0,
                    value4: '2023-01-07'
                }
            }
        },
        computed: {
            //将需要统一监听的数据进行拼接
            calculation1() {
                return this.value1 + '' + this.object1.value3 + '' + this.object1.value4
            }
        },
        watch: {
            //直接监听拼接后的数据
            calculation1(newValue, oldValue) {
                console.log('value1,value3,value4其中一个有变化')
            }
        },
    }
</script>
<style>
</style>

2.vue3组合式api写法

<template>
  <el-input v-model.number="value1" />
  <el-input v-model.number="value2" />
  <el-input v-model.number="object1.value3" />
  <el-date-picker v-model="object1.value4" type="date" value-format="YYYY-MM-DD" />
</template>
<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
const value1 = ref(0)
const value2 = ref(0)
const object1 = reactive({
  value3: 0,
  value4: '2023-01-07'
})
//将需要统一监听的数据进行拼接,我这里监听的 value1,object1.value3和object.value4三个数据
const calculation1 = computed(() => {
  return value1.value + '' + object1.value3 + '' + object1.value4
})
//直接监听拼接后的数据
watch(calculation1, () => {
  console.log('value1,value3,value4其中一个有变化')
})
</script>
<style>
</style>

 

posted @ 2023-01-07 14:37  时崎晓晓  阅读(2342)  评论(0编辑  收藏  举报