其他分享
首页 > 其他分享> > vue3-(toRef,toRefs,toRaw)

vue3-(toRef,toRefs,toRaw)

作者:互联网

1.toRef:从响应式对象上,创建一个新的ref对象

<template>
  <button @click="onChangeMsg">修改数据</button>
  <div>{{ obj.name }}</div>
</template>

<script setup lang="ts">
import { reactive, toRef } from 'vue';
let obj = reactive({
  name: '张三',
  age: 18,
  boj: {
    namespaced: true
  }
});
let name = toRef(obj, 'name');
setTimeout(() => {
  //可以修改
  name.value = '异步赋值';
}, 2000);
console.log('name', name);
const onChangeMsg = () => {
  name.value = '李四';
};
</script>

2.toRefs:可以帮我们批量创建ref对象主要是方便我们解构使用

<template>
  <button @click="onChangeMsg">修改数据</button>
  <div>{{ obj.name }}</div>
</template>

<script setup lang="ts">
import { reactive, toRefs } from 'vue';
let obj = reactive({
  name: '张三',
  age: 18,
  boj: {
    namespaced: true
  }
});
let { name, age, boj } = toRefs(obj);
setTimeout(() => {
  //可以修改
  name.value = '异步赋值';
}, 2000);
console.log('name', name);
console.log('age', age);
console.log('boj', boj);
const onChangeMsg = () => {
  name.value = '李四';
};
</script>

3.toRaw:将响应式对象修改为普通对象

<template>
  <button @click="onChangeMsg">修改数据</button>
  <div>{{ obj.name }}</div>
  <div>{{ toObj }}</div>
</template>

<script setup lang="ts">
import { reactive, toRaw } from 'vue';
let obj = reactive({
  name: '张三',
  age: 18,
  boj: {
    namespaced: true
  }
});
let toObj = toRaw(obj);
setTimeout(() => {
  //可以修改
  toObj.name = '异步赋值';
}, 2000);
const onChangeMsg = () => {
  toObj.name = '李四';
};
console.log('toObj', toObj);
</script>

 

标签:obj,name,age,toRefs,toObj,reactive,toRaw,let,toRef
来源: https://www.cnblogs.com/bzqs/p/16477692.html