04vue3.2-组合式API-computed和watch

2024-02-09  本文已影响0人  东邪_黄药师

computed

计算属性基本思想和Vue2保持一致,组合式API下的计算属性只是修改了API写法

<script setup>
 import { ref } from 'vue'
 // 准备好的数组
 const list = ref([1,2,3,4,5,6,7,8,9])
 // 引入computed 
 import { computed } from "vue";
//  过滤小于2的数据
 const computedList = computed(()=>{
  return list.value.filter(item =>{
    return item > 2
  })
 })

 // 乘以2额数组
const doubleCount = computed(()=>{
  return list.value.map(item =>{
    return item * 2
  })
})
</script>
<template>
 <div>原始数组---{{ list  }}</div>
 <div>过滤小于2的数据---{{ computedList }}</div>
 <div>乘以2额数组---{{  doubleCount  }}</div>
</template>
image.png

watch

侦听一个或者多个数据的变化,数据变化时执行回调函数,俩个额外参数 immediate控制立刻执行,deep开启深度侦听

1. 侦听单个数据

监听某一个值的时候

<script setup>
  // 1. 导入watch
  import { ref, watch } from 'vue'
  const count = ref(0)
  // 2. 调用watch 侦听变化
  watch(count, (newValue, oldValue)=>{
    console.log(`count发生了变化,老值为${oldValue},新值为${newValue}`)
  })
</script>

监听对象的某个属性的时候要写成回调函数

<script setup>
 // 导入
 import { reactive, watch } from 'vue'
 // 执行函数 传入参数 变量接收
 const state = reactive({
   count:0
 })
 const setSate = ()=>{
   // 修改数据更新视图
   state.count ++
 }
 // 监听对象的某个属性的时候要写成箭头函数
 watch(()=>state.count, (newVal,oldVal)=>{
  console.log(`count发生了变化,老值为${oldVal},新值为${oldVal}`)
 })
</script>
<template>
  {{ state.count }}
  <button @click="setSate">自加1</button>
</template>
image.png
2.侦听多个数据

侦听多个数据,第一个参数可以改写成数组的写法

<script setup>
  // 1. 导入watch
  import { ref, watch } from 'vue'
  const count = ref(0)
  const name = ref('zhangsan')
  const countClike = () =>{
    count.value ++
  }
  const countName = () =>{
    name.value = 'lisi'
  }
  // // 2. 调用watch 侦听变化
  watch([count, name], ([newCount, newName],[oldCount,oldName])=>{
    console.log('count或者name变化了',[newCount, newName],[oldCount,oldName])
  })
</script>
<template>
  <div>
    <div>{{ count }} <button @click="countClike">改变count</button></div>
    <div>{{ name }}  <button @click="countName">改变name</button></div>
  </div>
</template>
image.png
3. immediate

在侦听器创建时立即出发回调,响应式数据变化之后继续执行回调

<script setup>
  // 1. 导入watch
  import { ref, watch } from 'vue'
  const count = ref(0)
  // 2. 调用watch 侦听变化
  watch(count, (newValue, oldValue)=>{
    console.log(`count发生了变化,老值为${oldValue},新值为${newValue}`)
  },{
    immediate: true
  })
</script>
4. deep

通过watch监听的ref对象默认是浅层侦听的,直接修改嵌套的对象属性不会触发回调执行,需要开启deep
注:监听对象的某个属性的时候要写成回调函数(上文已说明)

<script setup>
 // 导入
 import { reactive, watch } from 'vue'
 // 执行函数 传入参数 变量接收
 const state = reactive({
   count:0
 })
 const setSate = ()=>{
   // 修改数据更新视图
   state.count ++
 }
 // 监听对象的某个属性的时候要写成箭头函数
 watch(state, (newVal,oldVal)=>{
  console.log('数据变化了')
 },{deep:true})
</script>
<template>
  {{ state.count }}
  <button @click="setSate">自加1</button>
</template>
image.png
上一篇 下一篇

猜你喜欢

热点阅读