<script setup>如何使用多个 watch

<script setup>
import { watch, defineProps, reactive } from "vue"

const props = defineProps({
  'nodeId': {
    type: Number,
    required: true,
  },
})

const initState = {
  connectionList: {},
}

const state = reactive(initState);

watch(
  () => props.nodeId,
  (newVal, oldVal)=> {
    console.log('nodeId changed', oldVal, newVal)
  },
)

watch(
  () => state.connectionList,
  (newVal, oldVal)=> {
    console.log('state.connectionNumEchartList changed', oldVal, newVal)
  },
)
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
关于使用 Vue3 + TypeScript + Vite 并且使用 `<script lang="ts" setup>` 语法时 `watch` 函数无效的问题,可能是由于使用了错误的语法或没有正确引用到响应式变量。 在 `<script lang="ts" setup>` 中,应该使用 `watchEffect` 函数或 `watch` 函数监听响应式变量的变化,具体使用哪一个函数取决于你的需求。如果你需要监听一个具体的响应式变量,可以使用 `watch` 函数;如果你需要监听多个响应式变量,或者需要在监听函数中访问其他响应式变量或组件实例,可以使用 `watchEffect` 函数。 下面是一个使用 `watch` 函数监听响应式变量的示例: ```vue <template> <div>{{ count }}</div> </template> <script lang="ts" setup> import { defineComponent, ref, watch } from 'vue' const count = ref(0) watch(count, (newValue, oldValue) => { console.log('count changed', newValue, oldValue) }) </script> ``` 在上面的示例中,我们使用 `ref` 函数定义了响应式变量 `count`,然后使用 `watch` 函数监听 `count` 的变化。如果 `count` 的值发生变化,`watch` 函数会被调用,并打印出变化前后的值。 如果你需要监听多个响应式变量,可以使用 `watchEffect` 函数,例如: ```vue <template> <div>{{ count1 }}, {{ count2 }}</div> </template> <script lang="ts" setup> import { defineComponent, ref, watchEffect } from 'vue' const count1 = ref(0) const count2 = ref(0) watchEffect(() => { console.log('count1 or count2 changed', count1.value, count2.value) }) </script> ``` 在上面的示例中,我们使用 `ref` 函数定义了响应式变量 `count1` 和 `count2`,然后使用 `watchEffect` 函数监听它们的变化。如果 `count1` 或 `count2` 的值发生变化,`watchEffect` 函数会被调用,并打印出变化前后的值。 希望这个解答能够帮到你!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值