小纸条1号
小纸条1号
发布于 2025-09-05 / 2 阅读
0

vue3小白,基础3,响应式API

1、ref

ref创建基本类型的响应式数据。也可以

2、reactive

reactive 创建对象类型的响应式数据,响应式数据是深层次的

3、toRefs 和 toRef

将一个响应式对象中的每一个属性,转换为ref对象

toRefstoRef功能一致,toRefs可以批量转换。

// 数据
  let person = reactive({name:'张三', age:18, gender:'男'})
	
  // 通过toRefs将person对象中的n个属性批量取出,且依然保持响应式的能力
  let {name,gender} =  toRefs(person)
	
  // 通过toRef将person对象中的gender属性取出,且依然保持响应式的能力
  let age = toRef(person,'age')

4、computed

根据已有数据计算出新数据

let fullName = computed(()=>{
    return firstName.value + '-' + lastName.value
  })

5、watch

监视数据的变化

1、ref定义的数据。

2、reactive定义的数据

3、函数返回一个值(getter函数)

4、一个包含上述内容的数组。

let sum = ref(0)
// 监视【ref】定义的【基本类型】数据
  const stopWatch = watch(sum,(newValue,oldValue)=>{
    console.log('sum变化了',newValue,oldValue)
    if(newValue >= 10){
      stopWatch()
    }
  })

6、watchEffect

立即运行一个函数,同时响应式地追踪其依赖,并在依赖更改时重新执行该函数。

  let temp = ref(0)
  let height = ref(0)
// 用watchEffect实现,不用指定属性
  const stopWtach = watchEffect(()=>{
    if(temp.value >= 50 || height.value >= 20){
      console.log('调用后台接口记录')
    }
    
    if(temp.value === 100 || height.value === 50){
      console.log('清理了')
      stopWtach()
    }
  })