vue3+ts 数值改变时重新运行
时间: 2023-02-08 21:57:04 浏览: 75
在 Vue3 中使用 TypeScript 时,如果想要在数值改变时重新运行,可以在计算属性或者 watcher 中监听数值的变化并在变化时触发相应的逻辑。
例如,在计算属性中监听数值的变化:
```
<template>
<div>
<input v-model="num" type="number">
<p>{{ computedNum }}</p>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue'
export default defineComponent({
name: 'MyComponent',
setup() {
const num = ref(0)
const computedNum = computed(() => num.value * 2)
return { num, computedNum }
}
})
</script>
```
或者在watch中监听:
```
<template>
<div>
<input v-model="num" type="number">
</div>
</template>
<script lang="ts">
import { defineComponent, ref, watch } from 'vue'
export default defineComponent({
name: 'MyComponent',
setup() {
const num = ref(0)
watch(num, (newVal, oldVal) => {
console.log(`num changed from ${oldVal} to ${newVal}`)
})
return { num }
}
})
</script>
```
这两种方式都可以达到监听数值变化并重新运行的目的.