Vue3基础六__shallowRef_triggerRef

回顾

ref

ref生成的数据能在页面发生响应式变化前提是改变ref数据.value下面的值

<template>
  <div>
    <p>refNum:{
     {
      refNum.age }}</p>
    <p>shallowRefNum:{
     {
      shallowRefNum.age }}</p>
    <button  @click="isFun">点击数字加1</button>
  </div>
</template>

<script>
import {
      ref,shallowRef } from "vue";

export default {
     
  name: "App",
  setup() {
     
    //首先创建一个ref响应数据
    let refNum  =ref({
     age:18})
    let shallowRefNum = shallowRef({
     age:18})
    function isFun() {
     
        refNum.value.age ++;
        // shallowRefNum.value.age++
    }
    return {
     refNum,isFun,shallowRefNum}
  },
};
</script>

当我们再点击页面的时候,页面上的

<p>refNum:{
     {
      refNum }}</p>

用ref生成的数据通过方法isFun发生了变化,点一下按钮数据+1;

而下面的用shallowRef生成的响应式数据并不会发生变化

<template>
  <div>
    <p>refNum:{
     {
      refNum.age }}</p>
    <p>shallowRefNum:{
     {
      shallowRefNum.age }}</p>
    <button  @click="isFun">点击数字加1</button>
  </div>
</template>

<script>
import {
      ref,shallowRef } from "vue";

export default {
     
  name: "App",
  setup() {
     
    //首先创建一个ref响应数据
    let refNum  =ref({
     age:18})
    let shallowRefNum = shallowRef({
     age:18})
    function isFun() {
     
        // refNum.value.age ++;
        shallowRefNum.value.age++
    }
    return {
     refNum,isFun,shallowRefNum}
  },
};
</script>

原因在于用shallowRef生成的数据只有第一层key是响应式的,因为ref数据有一个特点,会默认加一个value属性,传入的对象默认会作为value的属性值,所有用shallowRef生成的响应式数据只有value是响应的,是能达到响应式效果的,如果想将页面UI改变我们可以使用下面的方法

triggerRef

同样将上面用shallowRef生成响应式数据

<template>
  <div>
    <p>refNum:{
     {
      refNum.age }}</p>
    <p>shallowRefNum:{
     {
      shallowRefNum.age }}</p>
    <button  @click="isFun">点击数字加1</button>
  </div>
</template>

<script>
import {
      ref,shallowRef,triggerRef } from "vue";

export default {
     
  name: "App",
  setup() {
     
    //首先创建一个ref响应数据
    let refNum  =ref({
     age:18})
    let shallowRefNum = shallowRef({
     age:18})
    function isFun() {
     
        // refNum.value.age ++;
        shallowRefNum.value.age++
        triggerRef(shallowRefNum)
    }
    return {
     refNum,isFun,shallowRefNum}
  },
};
</script>

triggerRef 的作用就是将ref生成的数据强制再页面更新ui;
手动执行与 shallowRef(#shallowref) 关联的任何效果。

你可能感兴趣的:(vue,js,vue,js)