Vue3 中 setup,ref 和 reactive 的理解

setup

Vue3中使用了Composition API这种写法,使得所有的组合API函数都在此使用, 只在初始化时执行一次。
函数如果返回对象, 对象中的属性或方法, 模板中可以直接使用

ref

作用:定义一个数据的响应式
语法:const xxx = ref(initValue)
一般用来定义一个基本类型的响应式数据

  • 创建一个包含响应式数据的引用(reference)对象
  • js中操作数据: xxx.value
  • 模板中操作数据: 不需要.value

结合setup 和 ref 使用说明

其中vue2的写法为:

<template>
  <h2>{{count}}h2>
  <hr>
  <button @click="update">更新button>
template>

<script>
export default {
  /* 在Vue3中依然可以使用data和methods配置, 但建议使用其新语法实现 */
   data () {
     return {
       count: 0
     }
   },
   methods: {
     update () {
       this.count++
     }
   }
}
script>

vue3的写法为:

  1. setup最终会返回一个对象,并且对象中的值可以在模板中使用,如count
  2. 保证响应式,必须使用ref
<template>
  <h2>{{count}}h2>
  <hr>
  <button @click="update">更新button>
template>

<script>
import {
  ref
} from 'vue'
export default {
  /* 使用vue3的composition API */
  setup () {
    // 定义响应式数据 ref对象
    const count = ref(1)
    console.log(count)

    // 更新响应式数据的函数
    function update () {
      count.value = count.value + 1
    }

    return {
      count,
      update
    }
  }
}
script>

reactive

作用:定义多个数据的响应式,例如一个对象;
const isProxy = reactive(obj): 接收一个普通对象然后返回该普通对象的响应式代理器对象
响应式转换是“深层的”:会影响对象内部所有嵌套的属性
内部基于 ES6 的 Proxy 实现,通过代理对象操作源对象内部数据都是响应式的

<template>
  <h2>name: {{state.name}}h2>
  <h2>age: {{state.age}}h2>
  <h2>wife: {{state.wife}}h2>
  <hr>
  <button @click="update">更新button>
template>

<script>
import { reactive } from 'vue'
export default {
  setup () {
    /*  定义响应式数据对象 */
    let obj = {
      name: 'tom',
      age: 25,
      wife: {
        name: 'marry',
        age: 22
      },
    };
    // 此时state通过 reactive代理了obj,使其内属性成为响应式的;
    const state = reactive(obj)
    // 此时打印state 会得到一个Proxy的一个对象
    // state---代理对象,obj---目标对象
    console.log(state)

    const update = () => {
      state.name += '--'
      state.age += 1
      state.wife.name += '++'
      state.wife.age += 2
    }

    return {
      state,
      update,
    }
  }
}
script>

总结:如果操作代理对象,目标对象中的值也会跟着改变,如果想要页面跟着渲染,也是操作代理对象;

vue3响应式虽然写起来麻烦,但是减少了vue2响应式带来的性能开销

你可能感兴趣的:(vue3,vue.js,前端,javascript)