网站首页 > 博客文章 正文
了解ref()、reactive()这两个特性之前,我们先回顾一下vue2中data和method方法。在vue2中我们定义一个响应式变量name,通过点击事件handle来改变name的值是通过如下方式写的。这样只要name改变则界面相应的会发生改变,这就是数据的双向绑定。
<template>
{{name}}
<template>
<script>
export default {
data() {
return {
name:''
}
},
methods: {
handle(val) {
this.name = val
}
}
}
</script>
那么在vue3.0中,我们怎么定义响应式变量呢?我们下面对ref()、reactive()、toRefs()这三个方法进行讲解。
1、ref() 函数
ref() 函数用来根据给定的值创建一个响应式的数据对象,传入的为基本数据类型,例如字符串、数字、boolean 等,返回值是一个对象,这个对象上只包含一个 value 属性, 只在setup函数内部访问ref函数需要加.value
<script lang="ts">
import { defineComponent, ref } from 'vue';
export default defineComponent({
setup() {
const name = ref<string>('张三')
// 在js 中获取ref 中定义的值, 需要通过value属性
console.log(name.value);
// 同时定义的响应变量比如return出去,不然界面不会生效,
// 就像vue2中data里面的值需要return一个道理
return {
name
}
}
});
</script>
2、reactive() 函数
reactive函数传入的为引用类型,例如数组、对象等,但不能代理基本类型值,返回一个响应式的数据对象, 想要使用创建的响应式数据也很简单,创建出来之后,在setup中return出去,直接在template中调用即可。
<template>
{{state.name}}
<template>
<script lang="ts">
import { defineComponent, reactive, ref, toRefs } from 'vue';
export default defineComponent({
setup(props, context) {
let state = reactive({
name: 'test'
});
return {
state
}
}
});
</script>
3、toRefs() 函数
toRefs() 函数可以将 reactive() 创建出来的响应式对象,转换为普通的对象,类似使用拓展用算符...的方法返回数据data,使用方法如下
<template>
// 加了toRefs使用和reactive()函数区别在于可以直接使用name属性
{{name}}
<template>
<script lang="ts">
import { defineComponent, reactive, ref, toRefs } from 'vue';
export default defineComponent({
setup(props, context) {
let state = reactive({
name: 'test'
});
return {
// 关键点在这里
toRefs(state)
}
}
});
</script>
猜你喜欢
- 2024-10-04 Vue3的使用toRef和toRefs(vue torefs)
- 2024-10-04 Vue3教程 5.响应式toRef和toRefs函数
- 2024-10-04 vue3的readonly、shallowReadonly、shallowReactive、shallowRef
- 2024-10-04 全网首发:Vue3.5 源码 useTemplateRef #vue
- 2024-10-04 一起学习vue3Ts-ref全家桶(vue3.0全家桶最全入门指南)
- 2024-10-04 Vue语法之ref reactive对比及使用场景
- 2024-10-04 吃瓜!前端人因 Vue3 的 Ref 语法糖提案打起来了
- 2024-10-04 终于搞懂了!原来vue3中template使用ref无需.value是因为这个
- 2024-10-04 vue通过ref实现子父通信(vue父子组件如何通信)
- 2024-10-04 [Vue 3] 为什么需要同时使用Ref和Reactive
你 发表评论:
欢迎- 最近发表
- 标签列表
-
- ifneq (61)
- 字符串长度在线 (61)
- googlecloud (64)
- messagesource (56)
- promise.race (63)
- 2019cad序列号和密钥激活码 (62)
- window.performance (66)
- qt删除文件夹 (72)
- mysqlcaching_sha2_password (64)
- ubuntu升级gcc (58)
- nacos启动失败 (64)
- ssh-add (70)
- jwt漏洞 (58)
- macos14下载 (58)
- yarnnode (62)
- abstractqueuedsynchronizer (64)
- source~/.bashrc没有那个文件或目录 (65)
- springboot整合activiti工作流 (70)
- jmeter插件下载 (61)
- 抓包分析 (60)
- idea创建mavenweb项目 (65)
- vue回到顶部 (57)
- qcombobox样式表 (68)
- tomcatundertow (58)
- pastemac (61)
本文暂时没有评论,来添加一个吧(●'◡'●)