vue的watch和computed的使用

1. watch

<template>
  <div>
    <div>{
   
   { num }}</div>
    <button @click="onAdd">点击</button>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
const num = ref(1)
const onAdd = () => {
  num.value += 1
}

// watch监听(要监听的属性,回调函数, 配置对象)  watch相当于一个方法
watch(
  num,
  () => {
    console.log('num改变了')
  },
  {
    deep: true,
    immediate: true
  }
)
</script>

<style></style>

2. computed

<template>
  <div>
    <div>{
   
   { num }}</div>
    <div>{
   
   { number }}</div>
    <button @click="onAdd">点击</button>
  </div>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
const num = ref(1)
const onAdd = () => {
  num.value += 1
}

// watch监听(要监听的属性,回调函数)  watch相当于一个方法
watch(
  num,
  () => {
    console.log('num改变了')
  },
  {
    deep: true,
    immediate: true
  }
)
const number = computed(() => {
  return '当前数字为' + num.value
})
</script>

<style></style>

猜你喜欢

转载自blog.csdn.net/m0_59338367/article/details/126472115