vue3.0之ref函数

<template><div>{{count}}</div></template><script>import {ref} from 'vue'export default {setup(){const count = ref(10)console.log(count.value) // 10}}</script>
4、若使用ref定义复杂类型数据,则监听不到数据的变动,实际是走了reactive (const convert = (val) => isObject(val) ? reactive(val) : val)
<script>import {ref, watch} from 'vue'export default {setup(){const arr = [1,2,3]setTimeout(() => {arr.value[0] = 0}, 1500)watch(arr, (nelVal) => { // 监听不到arr的变化})}}</script>
5、ref函数的实现
(1)craeteRef 创建ref对象(将基本数据类型转为复杂数据类型)function createRef(rawValue, shallow = false) {if (isRef(rawValue)) {return rawValue;}return new RefImpl(rawValue, shallow);}(2)RefImpl 类(如果传递 shallow = true 则只是代理最外层)class RefImpl {constructor(value, _shallow = false) {this._shallow = _shallow;this.__v_isRef = true;this._rawValue = _shallow ? value : toRaw(value);this._value = _shallow ? value : convert(value); // const convert = (val) => isObject(val) ? reactive(val) : val;}get value() { // value 属性访问器track(toRaw(this), "get" /* GET */, 'value');return this._value;}set value(newVal) { // value 属性设置器newVal = this._shallow ? newVal : toRaw(newVal);if (hasChanged(newVal, this._rawValue)) { // 判断新老值是否有变化,改变就更新值,trigger 触发依赖执行this._rawValue = newVal;this._value = this._shallow ? newVal : convert(newVal);trigger(toRaw(this), "set" /* SET */, 'value', newVal);}}}
本文完~
学习更多技能
请点击下方公众号
![]()

评论
