toRaw
ref
<template>
<div>
<p>name:{
{
strObj.name}}</p>
<p>age:{
{
strObj.age}}</p>
<button @click="isChangeFun">点击按钮年龄加1</button>
</div>
</template>
<script>
import {
ref ,toRaw} from "vue";
export default {
name: "App",
setup() {
let strObj1={
name:"zjq",
age:188
}
let strObj = ref(strObj1)
const isChangeFun = ()=>{
strObj.value.age++
let toRawStrObj = toRaw(strObj.value)
console.log(toRawStrObj);
}
return {
strObj,isChangeFun}
},
};
</script>
toRaw方法能获取到ref的原始对象,前提是需要.value,将ref对象转成普通对象,因为对象在ref的value属性上,所以我们在获取原始数据的时候需要.value。
reactive
<template>
<div>
<p>name:{
{
strObj.name}}</p>
<p>age:{
{
strObj.age}}</p>
<button @click="isChangeFun">点击按钮年龄加1</button>
</div>
</template>
<script>
import {
reactive ,toRaw} from "vue";
export default {
name: "App",
setup() {
let strObj1={
name:"zjq",
age:188
}
let strObj = reactive(strObj1)
const isChangeFun = ()=>{
strObj.value.age++
let toRawStrObj = toRaw(strObj)
console.log(toRawStrObj);
}
return {
strObj,isChangeFun}
},
};
</script>
利用reactive包裹的响应式数据获取原始数据直接就可以获取到,这也是ref和reactive的特点。
markRaw
ref
<template>
<div>
<p>name:{
{
strObj.name}}</p>
<p>age:{
{
strObj.age}}</p>
<button @click="isChangeFun">点击按钮年龄加1</button>
</div>
</template>
<script>
import {
ref ,markRaw} from "vue";
export default {
name: "App",
setup() {
let strObj1={
name:"zjq",
age:188
}
let strObj = markRaw(strObj1)
let strObjRef = ref(strObj)
const isChangeFun = ()=>{
strObjRef.value.age++
console.log('strObjRef.value===', strObjRef.value);
}
return {
strObj,isChangeFun}
},
};
</script>
使用markRaw包裹之后的对象,永远不能转成响应式数据,即使使用ref包裹。
页面不会发生改变。
reactive
<template>
<div>
<p>name:{
{
strObj.name}}</p>
<p>age:{
{
strObj.age}}</p>
<button @click="isChangeFun">点击按钮年龄加1</button>
</div>
</template>
<script>
import {
reactive ,markRaw} from "vue";
export default {
name: "App",
setup() {
let strObj1={
name:"zjq",
age:188
}
let strObj = markRaw(strObj1)
let strObjRef = reactive(strObj)
const isChangeFun = ()=>{
strObjRef.age++
console.log('strObjRef===', strObjRef);
}
return {
strObj,isChangeFun}
},
};
</script>
reactive包裹也同样如此,无法更新UI界面。
转载:https://blog.csdn.net/qq_43291759/article/details/117388719
查看评论