AVt天堂网 手机版,亚洲va久久久噜噜噜久久4399,天天综合亚洲色在线精品,亚洲一级Av无码毛片久久精品

當前位置:首頁 > 科技  > 軟件

終于搞懂了!原來Vue3中Template使用Ref無需.Value是因為這個

來源: 責編: 時間:2024-06-06 17:41:10 122觀看
導讀前言眾所周知,vue3的template中使用ref變量無需使用.value。還可以在事件處理器中進行賦值操作時,無需使用.value就可以直接修改ref變量的值,比如:<button @click="msg = 'Hello Vue3'">change msg</button>。你猜vue是在

前言

眾所周知,vue3的template中使用ref變量無需使用.value。還可以在事件處理器中進行賦值操作時,無需使用.value就可以直接修改ref變量的值,比如:<button @click="msg = 'Hello Vue3'">change msg</button>。你猜vue是在編譯時就已經在代碼中生成了.value,還是運行時使用Proxy攔截的方式去實現的呢?注:本文中使用的vue版本為3.4.19。3Mu28資訊網——每日最新資訊28at.com

看個demo

看個簡單的demo,代碼如下:3Mu28資訊網——每日最新資訊28at.com

<template>  <p>{{ msg }}</p>  <button @click="msg = 'Hello Vue3'">change msg</button></template><script setup lang="ts">import { ref } from "vue";const msg = ref("Hello World");console.log(msg.value);</script>

上面的代碼很簡單,在script中想要訪問msg變量的值需要使用msg.value。但是在template中將msg變量渲染到p標簽上面時就是直接使用{{ msg }},在click的事件處理器中給msg變量賦新的值時也沒有使用到.value。3Mu28資訊網——每日最新資訊28at.com

然后在瀏覽器中找到上面這個vue文件編譯后的樣子,在之前的文章中已經講過很多次如何在瀏覽器中查看編譯后的vue文件,這篇文章就不贅述了。編譯后的代碼如下:3Mu28資訊網——每日最新資訊28at.com

import {  Fragment as _Fragment,  createElementBlock as _createElementBlock,  createElementVNode as _createElementVNode,  defineComponent as _defineComponent,  openBlock as _openBlock,  toDisplayString as _toDisplayString,  ref,} from "/node_modules/.vite/deps/vue.js?v=23bfe016";const _sfc_main = _defineComponent({  __name: "index",  setup() {    const msg = ref("Hello World");    console.log(msg.value);    const __returned__ = { msg };    return __returned__;  },});function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {  return (    _openBlock(),    _createElementBlock(      _Fragment,      null,      [        _createElementVNode("p", null, _toDisplayString($setup.msg), 1),        _createElementVNode(          "button",          {            onClick:              _cache[0] ||              (_cache[0] = ($event) => ($setup.msg = "Hello Vue3")),          },          "change msg"        ),      ],      64    )  );}_sfc_main.render = _sfc_render;export default _sfc_main;

vue文件編譯后的代碼主要分為兩塊:_sfc_main和_sfc_render。3Mu28資訊網——每日最新資訊28at.com

  • _sfc_main中主要是setup方法,這個是vue的<script setup lang="ts">部分編譯后的樣子。從上面可以看到在編譯后的setup方法中,訪問msg變量時依然使用了msg.value,并且在setup方法中return了{ msg }對象。
  • _sfc_render就是我們熟悉的render函數,在render函數中渲染p標簽部分的內容是:_toDisplayString($setup.msg)。很明顯這個toDisplayString就是一個將輸入值轉換為字符串的函數,并沒有處理.value。$setup.msg中的$setup.,我想你猜到了應該和前面這個setup方法中return的{ msg }對象有關,但是又不是直接使用setup方法中return的{ msg }對象,因為使用setup中的msg變量需要使用.value,在編譯后的render函數中并沒有幫我們自動生成一個.value,比如這樣的代碼:$setup.msg.value。同樣的在render函數中,button的click事件給msg變量賦值時也沒有幫我們生成一個類似于這樣的代碼:$setup.msg.value = "Hello Vue3",而是$setup.msg = "Hello Vue3"。從render函數中可以看出在template中使用ref變量無需使用.value,并不是編譯時就已經在代碼中生成了.value,比如$setup.msg.value,而是通過Proxy的方式去實現的。

render函數

在render函數中讀和寫msg變量都變成了$setup.msg,而這個$setup對象又是調用render函數時傳入的第四個參數。現在我們需要搞清楚調用render函數時傳入的第四個參數到底是什么?給render函數打一個斷點,刷新頁面,此時代碼走到了斷點里面,如下圖:3Mu28資訊網——每日最新資訊28at.com

圖片圖片3Mu28資訊網——每日最新資訊28at.com

右邊的Call Stack表示當前函數的調用鏈,從調用鏈中可以看到render函數是由一個名為renderComponentRoot的函數調用的。3Mu28資訊網——每日最新資訊28at.com

點擊Call Stack中的renderComponentRoot,代碼會跳轉到renderComponentRoot函數中,在我們這個場景中簡化后的renderComponentRoot函數代碼如下:3Mu28資訊網——每日最新資訊28at.com

function renderComponentRoot(instance) {  const {    props,    data,    setupState,    render: render2,    // 省略...  } = instance;  render2.call(    thisProxy,    proxyToUse,    renderCache,    props,    setupState,    data,    ctx  );}

這里的render2也就是我們的render函數,由于使用了.call,所以調用render函數時傳入的第四個參數為setupState對象。而setupState對象的值又是從instance.setupState而來的。3Mu28資訊網——每日最新資訊28at.com

通過debug調試render函數我們發現,在render函數中渲染msg變量是使用$setup.msg,而$setup對象的值是從instance.setupState對象上面來的。3Mu28資訊網——每日最新資訊28at.com

前面講過了編譯后的setup方法會返回一個包含msg屬性的對象,而這個$setup對象也就是instance.setupState肯定是和setup方法返回的對象有關系的。所以接下來我們需要去debug調試setup方法搞清楚他們到底是什么關系。3Mu28資訊網——每日最新資訊28at.com

setup方法

將render函數中的斷點去掉,然后給setup方法打一個斷點。刷新頁面,此時代碼會走到斷點中,如下圖:圖片3Mu28資訊網——每日最新資訊28at.com

同理在Call Stack中可以看到調用setup方法的是callWithErrorHandling函數,點擊Call Stack中的callWithErrorHandling,代碼會跳轉到callWithErrorHandling函數中。代碼如下:3Mu28資訊網——每日最新資訊28at.com

function callWithErrorHandling(fn, instance, type, args) {  try {    return args ? fn(...args) : fn();  } catch (err) {    handleError(err, instance, type);  }}

從上面可以看到在callWithErrorHandling函數中只是進行了錯誤處理,并不是我們想要找的。3Mu28資訊網——每日最新資訊28at.com

setupStatefulComponent函數

從Call Stack中可以看到調用callWithErrorHandling函數的是setupStatefulComponent函數,點擊Call Stack中的setupStatefulComponent,代碼會跳轉到setupStatefulComponent函數中。在我們這個場景中簡化后的setupStatefulComponent函數代碼如下:3Mu28資訊網——每日最新資訊28at.com

function setupStatefulComponent(instance) {  const Component = instance.type;  const { setup } = Component;  const setupResult = callWithErrorHandling(setup, instance);  handleSetupResult(instance, setupResult);}

從上面的代碼可以看到確實是使用callWithErrorHandling函數執行了setup方法,并且還將setup方法的返回值對象賦值給了setupResult變量。然后以instance(vue實例)和setupResult(setup方法的返回值)為參數,調用了handleSetupResult函數。3Mu28資訊網——每日最新資訊28at.com

handleSetupResult函數

將斷點走進handleSetupResult函數,在我們這個場景中簡化后的handleSetupResult函數代碼如下:3Mu28資訊網——每日最新資訊28at.com

function handleSetupResult(instance, setupResult) {  instance.setupState = proxyRefs(setupResult);}

我們在render函數中渲染msg變量是使用$setup.msg,而$setup對象的值是從instance.setupState對象上面來的。3Mu28資訊網——每日最新資訊28at.com

現在我們已經找到了instance.setupState是在這里賦值的,它的值是proxyRefs函數的返回結果。3Mu28資訊網——每日最新資訊28at.com

proxyRefs函數

將斷點走進proxyRefs函數,代碼如下:3Mu28資訊網——每日最新資訊28at.com

function proxyRefs(objectWithRefs) {  return isReactive(objectWithRefs)    ? objectWithRefs    : new Proxy(objectWithRefs, shallowUnwrapHandlers);}

這個isReactive函數是vue暴露出來的一個API,它的作用是檢查一個對象是否是由 reactive() 或 shallowReactive() 創建的代理。3Mu28資訊網——每日最新資訊28at.com

這里的objectWithRefs對象就是setup方法的返回值對象,通過前面我們知道setup方法的返回值對象就是一個普通的js對象,并不是reactive的。所以proxyRefs函數會返回三目運算符冒號(:)后面的表達式,也就是使用Proxy創建的setup方法返回值對象代理。3Mu28資訊網——每日最新資訊28at.com

我們接著來看shallowUnwrapHandlers里面做了哪些事情,代碼如下:3Mu28資訊網——每日最新資訊28at.com

const shallowUnwrapHandlers = {  get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)),  set: (target, key, value, receiver) => {    const oldValue = target[key];    if (isRef(oldValue) && !isRef(value)) {      oldValue.value = value;      return true;    } else {      return Reflect.set(target, key, value, receiver);    }  },};

這個handler包含get和set方法,會對setup的返回值對象進行攔截。3Mu28資訊網——每日最新資訊28at.com

當在render函數中渲染p標簽時會去讀$setup.msg,就會走到get的攔截中。在get方法中使用到了Reflect.get方法和unref函數。3Mu28資訊網——每日最新資訊28at.com

  • Reflect.get(target, key, receiver)的作用是獲取target對象的key屬性,在我們這里就是獲取setup返回值對象的msg屬性,也就是我們定義的msg變量。并且這個msg變量是一個ref。
  • 將Reflect.get方法拿到的msg變量傳給unref函數,這個unref函數同樣是暴露出來的一個API。如果參數是 ref,則返回內部值,否則返回參數本身。這是 val = isRef(val) ? val.value : val 計算的一個語法糖。經過unref函數的處理后,在get攔截中return的就是.value后的內容,也就是msg.value。所以在template中使用ref變量無需使用.value,是因為在Proxy的get攔截中已經幫我們自動處理了.value。當在render函數中去對ref變量進行賦值,比如:<button @click="msg = 'Hello Vue3'">change msg</button>。就會走到set攔截中,首先會執行const oldValue = target[key]。這里的key就是"msg",target就是setup函數返回值對象。使用oldValue就是msg變量,是一個ref。

由于我們在click事件中要將msg賦值成'Hello Vue3'字符串,所以在set攔截中拿到的新value為'Hello Vue3'字符串。3Mu28資訊網——每日最新資訊28at.com

接著執行if (isRef(oldValue) && !isRef(value))判斷,這里的oldValue前面已經講過了是一個名為msg的ref變量,所以isRef(oldValue) 為true。value為'Hello Vue3'字符串,所以!isRef(value)也是為true。3Mu28資訊網——每日最新資訊28at.com

代碼就會走進if判斷中執行oldValue.value = value,也就是在執行msg.value = 'Hello Vue3'。3Mu28資訊網——每日最新資訊28at.com

所以在template中給ref變量賦值無需使用.value,是因為在Proxy的set攔截中也幫我們自動處理了.value。3Mu28資訊網——每日最新資訊28at.com

總結

整個流程圖如下:3Mu28資訊網——每日最新資訊28at.com

圖片圖片3Mu28資訊網——每日最新資訊28at.com

在vue3的template中使用ref變量無需使用.value,是因為有個Proxy的get攔截,在get攔截中會自動幫我們去取ref變量的.value屬性。3Mu28資訊網——每日最新資訊28at.com

同樣的在template中對ref變量進行賦值也無需使用.value,也是有個Proxy的set攔截,在set攔截中會自動幫我們去給ref變量的.value屬性進行賦值。3Mu28資訊網——每日最新資訊28at.com

本文鏈接:http://www.tebozhan.com/showinfo-26-92462-0.html終于搞懂了!原來Vue3中Template使用Ref無需.Value是因為這個

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: 基于 Go 語言實現的 Ollama 大語言模型框架

下一篇: 解密Tenacity:Python中最強大的重試庫

標簽:
  • 熱門焦點
Top