防止观看的元素相互调用更新

问题描述 投票:0回答:1

如何防止观看的元素在 Vuejs 中相互调用更新?

const width = ref(0);
const height = ref(0);

watch(width, async (newItem, oldItem) => {
    console.log(`width: ${oldItem}->${newItem}`);
    height.value = newItem / 2;
});

watch(height, async (newItem, oldItem) => {
    console.log(`height: ${oldItem}->${newItem}`);
    width.value = newItem * 2;
});

结果,我可以在控制台中看到这样的输出

width: 1->2
height: 0.5->1
width: 2->2

完整的 vuejs 代码:

<script setup>
import { ref } from 'vue'
import { watch } from 'vue'

const width = ref(0);
const height = ref(0);

watch(width, async (newItem, oldItem) => {
    console.log(`width: ${oldItem}->${newItem}`);
    height.value = newItem / 2;
});

watch(height, async (newItem, oldItem) => {
    console.log(`height: ${oldItem}->${newItem}`);
    width.value = newItem * 2;
});
</script>

<template>
    <div class="item">
        <div class="details">
            <h3>
                Width {{ width }}
            </h3>
            <input v-model="width" placeholder="0" />
        </div>
    </div>

    <div class="item">
        <div class="details">
            <h3>
                Height {{ height }}
            </h3>
            <input v-model="height" placeholder="0" />
        </div>
    </div>
</template>

vue.js vuejs3
1个回答
0
投票

如果您使用

JSON.stringify
输出值,您会注意到由于计算,类型从字符串更改为数字: 游乐场

width: 0->"2"
height: 0->1
width: "2"->2

只需使用

v-model.number="width"
即可仅对数字进行操作:Playground

© www.soinside.com 2019 - 2024. All rights reserved.