# 1.unref 的用法
App 为根组件 下面 Home 例子都被此组件引用
// App.vue | |
<template> | |
<div> | |
<home></home> | |
</div> | |
</template> | |
<script> | |
import Home from "./Home.vue"; | |
export default { | |
components: { | |
Home, | |
}, | |
}; | |
</script> | |
<style scoped> | |
</style> |
// Home.vue | |
<template> | |
<div> | |
<h3>info:{{ info }}</h3> | |
</div> | |
</template> | |
<script> | |
import { ref, unref } from "vue"; | |
export default { | |
setup() { | |
const info = ref({ | |
name: "Neko", | |
age: 16, | |
}); | |
//unref 使用场景是:不确定是否是 普通对象还是 ref 对象,因为他们取值方式不同 | |
console.log(info); //ref 对象 | |
console.log(unref(info)); // 普通对象 | |
console.log(unref(info).age); // 可以不通过 value 直接取值 | |
return { info }; | |
}, | |
}; | |
</script> | |
<style scoped></style> |
参考结果:
# 2.isRef 的用法
// Home.vue | |
<template> | |
<div></div> | |
</template> | |
<script> | |
import { ref, isRef, reactive } from "vue"; | |
export default { | |
setup() { | |
const info = { | |
name: "Aphrodite", | |
age: 16, | |
}; | |
const infoRef = ref({ | |
name: "Neko", | |
age: 16, | |
}); | |
const infoReactive = reactive({ | |
name: "Nico", | |
age: 16, | |
}); | |
//isRef 顾名思义判断是否是 ref 对象 | |
console.log("info:", isRef(info)); // false | |
console.log("infoRef", isRef(infoRef)); // true | |
console.log("infoReactive", isRef(infoReactive)); // false | |
return { | |
info, | |
infoRef, | |
infoReactive, | |
}; | |
}, | |
}; | |
</script> | |
<style scoped></style> |
参考结果:
# 3. 总结
- unref:一般在别人传递数据时不确定是否是 ref 对象,取值的方式不同造成结果不同时,会使用的 API
- isRef:判断是否是 ref 对象