返回

vue3.0之ref函数

发布时间:2022-11-25 04:20:37 401
# webkit# 数据

vue3.0之ref函数_基本数据类型

 

1、ref推荐定义基本数据类型(ref值也可以是对象,但是一般情况下是对象直接使用reactive更合理)。

2、在 vue 的模板中使用 ref 的值不需要通过 value 获取 (vue 会通过自动给 ref 的值加上 .value)。

3、在 js 中使用 ref 的值必须使用 .value 获取。

 
<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);
}
}
}

本文完~

vue3.0之ref函数_数据_02

 

 

 

 

 

vue3.0之ref函数_基本数据类型_03

 

特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像
精选文章
thumb 中国研究员首次曝光美国国安局顶级后门—“方程式组织”
thumb 俄乌线上战争,网络攻击弥漫着数字硝烟
thumb 从网络安全角度了解俄罗斯入侵乌克兰的相关事件时间线