ref和reactive的使用

ref和reactive的使用场景区别

  • ref可以包装基本类型、数组、对象;reactive只能用来包装引用类型。
  • ref包装的数组和对象可以整体赋值,reactive包装的引用类型不能整体被赋值
  • ref在script中需要'.value'出来;reactive不需要

常常这样用

复制代码
1、基本类型用ref
let n = ref(0);
n.value = 1;
2、数组用ref
let arr = ref([1,2]);
arr.value = [1,2,3];
3、对象用reactive
let obj = reactive({name: 'jim'});
Object.assign(obj,{age: 18});  -> {name:'jim', age:18}

使用ref获取dom

复制代码
<div ref="xx">
API选项中:
this.$refs.xx
setup中:
const xx = ref(),在onMounted中使用

customRef(costomRef可以理解为被拦截的ref)

复制代码
const myRef = (value) => {
  return customRef((track, trigger) => {
    return {
      get() {
        track()
        return value
      },
      set(newValue) {
        if(newValue < 10) {
          value = newValue
          // 延迟渲染
          setTimeout(() => {
            trigger()
          }, 2000);
        }
      }
    }
  })
}

从reactive对象中解构出属性作为响应式数据使用

复制代码
let obj = reactive({
 name: 'jim',
 age: 18
})
let {name, age} = toRefs(obj) // 此时name和age就是响应式的数据
相关推荐
weixin_4407305026 分钟前
函数return、参数、参数组、递归函数、高阶函数等小结
开发语言·python
特创数字科技43 分钟前
一个纯本地运行的图片处理工具:压缩 / 裁剪 / 九宫格 / 圆角 / 滤镜 / 拼图 / 水印,终生使用
前端
sugarzhangnotes1 小时前
【无标题】
开发语言·人工智能·python
geovindu1 小时前
rust: Composite Pattern
开发语言·后端·设计模式·rust·组合模式
IT_陈寒1 小时前
Vue的v-if和v-for混用居然是个天坑
前端·人工智能·后端
天衍四九-1 小时前
【无标题】
前端·spring boot·mysql·nginx·docker
广州华水科技1 小时前
2026年单北斗GNSS变形监测系统推荐榜单,解锁GNSS位移监测新高度
前端
xcyxiner2 小时前
DicomViewer24 修复编译bug(window test 失败)
前端·qt
linux_cfan2 小时前
videojs v10 源代码系列解读:34 · `createComposition`:类型安全的冲突检测
前端·安全