VUE3-toRef函数与toRefs函数(13)

文章目录

    • toRef函数
    • toRefs函数

toRef函数

<template>
  <h3>{{ student }}h3>
  <h1>学生姓名:{{ name }}h1>
  <h1>学生年龄:{{ age }}h1>
  <h1>学生薪资:{{ job.web.salary }}Kh1>
  <hr>

  <button type="button" @click="name+='~'">修改姓名button>
  <button type="button" @click="age++">增长年龄button>
  <button type="button" @click="job.web.salary++">增长薪资button>
template>

<script>
import {reactive, toRef} from "vue";

export default {
  name: "TestExample",
  setup() {
    const student = reactive({
      name: '张三',
      age: 18,
      job: {
        web: {
          salary: 20
        }
      }
    })

    let name = toRef(student, 'name')
    console.log(name) // ObjectRefImpl {...}
    console.log(name.value) // 张三

    let job = toRef(student, 'job')
    console.log(job) // ObjectRefImpl {...}
    console.log(job.value) // Proxy {web: {...}}

    return {
      student,
      name,
      job,
      age: toRef(student, 'age')
    }
  }
}
script>

toRefs函数

<template>
  <h1>学生姓名:{{ name }}h1>
  <h1>学生年龄:{{ age }}h1>
  <h1>学生薪资:{{ job.web.salary }}Kh1>
  <hr>

  <button type="button" @click="name+='~'">修改姓名button>
  <button type="button" @click="age++">增长年龄button>
  <button type="button" @click="job.web.salary++">增长薪资button>
template>

<script>
import {reactive, toRefs} from "vue";

export default {
  name: "TestExample",
  setup() {
    const student = reactive({
      name: '张三',
      age: 18,
      job: {
        web: {
          salary: 20
        }
      }
    })

    let s = toRefs(student)
    console.log(s) // {name: ObjectRefImpl, age: ObjectRefImpl, job: ObjectRefImpl}
    console.log(s.name.value) // 张三
    console.log(s.age.value) // 18
    console.log(s.job.value) // Proxy {web: {...}}

    return {
      ...s
    }
  }
}
script>

你可能感兴趣的:(Vue学习笔记,vue.js)