toRef 顾名思义,不是ref 响应式数据,给它转成ref 响应式数据
通俗易懂的理解:
- <template>
- <h3>姓名:{{ person.name }}</h3>
- <h3>年龄:{{ person.age }}</h3>
- <h3>薪资:{{ person.job.j1.salary }}</h3>
- <button @click="person.name += '!'">修改姓名</button>
- <button @click="person.age++">增长年龄</button>
- <button @click="person.job.j1.salary++">涨薪</button>
- </template>
-
- <script>
- import { reactive } from "vue";
- export default {
- setup() {
- let person = reactive({
- name: "张三",
- age: 18,
- job: {
- j1: {
- salary: 20,
- },
- },
- });
- return {
- person,
- };
- },
- };
- </script>
-
- <style>
- </style>
首先实现功能没问题,接下来考虑到代码优化:

那可能会想到 我在return的时候,麻烦一些,
- return {
- name: person.name,
- age: person.age,
- job: person.job.j1.salary,
- };
但是,这样操作你会发现页面不是响应式的,数据修改页面不发生变化,如下:

接下来看 toRef的用法: 很明显实现了效果
- <template>
- <h3>姓名:{{ name }}</h3>
- <h3>年龄:{{ age }}</h3>
- <h3>薪资:{{ salary }}</h3>
- <button @click="name += '!'">修改姓名</button>
- <button @click="age++">增长年龄</button>
- <button @click="salary++">涨薪</button>
- </template>
-
- <script>
- import { reactive, toRef } from "vue";
- export default {
- setup() {
- let person = reactive({
- name: "张三",
- age: 18,
- job: {
- j1: {
- salary: 20,
- },
- },
- });
- return {
- name: toRef(person, "name"),
- age: toRef(person, "age"),
- salary: toRef(person.job.j1, "salary"),
- };
- },
- };
- </script>
-
- <style>
- </style>

介绍完toRef的用法之后,接下来来看一下toRefs的用法吧

到此这篇关于一文带你了解Vue3中toRef和toRefs的用法的文章就介绍到这了,更多相关Vue3 toRef toRefs用法内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!