Vue3属性绑定方法解析

 更新时间:2022年09月25日 09:54:33   作者:Web能力中心团队​​​​​​​  
这篇文章主要介绍了Vue3属性绑定方法解析,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下

前言:

这篇文章来自我们团队的田鑫雨同学,强劲的“后浪”。不论使用已有框架,还是自实现框架,数据绑定都是一个热点话题,来看看他对Vue3数据绑定方式的分析

Vue3 通常使用 v-bind 绑定数据到子元素上,对于一个元素接收数据的方式有两种:通过property或通过attribute,本文通过分析源码得到结论:Vue会通过判断元素实例el上是否有需要绑定的property,如果有就把数据传给子元素的property,否则传给attribute。当然还有会一些特殊处理,我们这里只讨论一般情况。

首先说结论,对于一般的属性,Vue会判断元素el上是否有对应的property属性,如果有就赋值给对应的property,否则添加到attribute上。然后Vue会对一些属性做特殊处理直接绑定到attribute,此外对input/textarea/select元素也会有特殊处理。

Vue3.2版本还提供了:xxx.prop 和 :xxx.attr 写法指定绑定数据到propertyattribute

直接从源码入手。

在Vue初始化过程中,Vue会将<template>解析并构造成vdom,收集其中的数据绑定放在props对象中。到了mount阶段Vue会根据vdom创建为真实DOM,然后放到页面中。

创建过程大致为遍历vdom中的vnode节点,执行mountElement(),关键代码如下,根据vnode创建真实el元素,进行数据绑定和事件绑定,然后把el元素插入到父容器中,最后完成页面的加载。

const mountElement = (vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
  let el;
  // ...
  const { type, props, shapeFlag, transition, patchFlag, dirs } = vnode;
  {
      el = vnode.el = hostCreateElement(vnode.type, isSVG, props && props.is, props);
      // ...
      // props
      if (props) {
          for (const key in props) {
              if (key !== 'value' && !isReservedProp(key)) {
                  hostPatchProp(el, key, null, props[key], isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
              }
          }
          // ...
      }
      // ...
  }
  // ...
  hostInsert(el, container, anchor);
  // ...
};

这里以一个自定义的WebComponent元素<te-tag>为例

Vue使用createElement创建了te-tag元素对象保存在el中,然后使用for (const key in props) {...}遍历需要绑定的属性,属性名为key,属性值为props[key],然后执行hostPatchProp()将该属性添加到el上。

hostPatchProp()patchProp()方法代码如下

const patchProp = (el, key, prevValue, nextValue, isSVG = false, prevChildren, parentComponent, parentSuspense, unmountChildren) => {
      if (key === 'class') {
          patchClass(el, nextValue, isSVG);
      }
      else if (key === 'style') {
          patchStyle(el, prevValue, nextValue);
      }
      else if (isOn(key)) {
          // ignore v-model listeners
          if (!isModelListener(key)) {
              patchEvent(el, key, prevValue, nextValue, parentComponent);
          }
      }
      else if (key[0] === '.'
          ? ((key = key.slice(1)), true)
          : key[0] === '^'
              ? ((key = key.slice(1)), false)
              : shouldSetAsProp(el, key, nextValue, isSVG)) {
          patchDOMProp(el, key, nextValue, prevChildren, parentComponent, parentSuspense, unmountChildren);
      }
      else {
          if (key === 'true-value') {
              el._trueValue = nextValue;
          }
          else if (key === 'false-value') {
              el._falseValue = nextValue;
          }
          patchAttr(el, key, nextValue, isSVG);
      }
  };

通过源码可以看到,除了class/style的属性,Vue会对我们自定义的属性会进行一个判断, 对于key的值:

  • .xxx表示通过:xxx.prop绑定的数据,直接往property上设置
  • ^xxx表示通过:xxx.attr绑定的值,应该往attribute上设置
  • 不是以上两种情况的key值如xxx,需要调用shouldSetAsProp()判断是否应该设置到property上

判断为真绑定property会执行patchDOMProp(),否则绑定attribute会执行pathAttr()

我们这里最关心的第三种情况执行shouldSetAsProp()来判断是否应该把xxx设置到property上,其代码如下

function shouldSetAsProp(el, key, value, isSVG) {
      if (isSVG) {
          // most keys must be set as attribute on svg elements to work
          // ...except innerHTML & textContent
          if (key === 'innerHTML' || key === 'textContent') {
              return true;
          }
          // or native onclick with function values
          if (key in el && nativeOnRE.test(key) && isFunction(value)) {
              return true;
          }
          return false;
      }
      // these are enumerated attrs, however their corresponding DOM properties
      // are actually booleans - this leads to setting it with a string "false"
      // value leading it to be coerced to `true`, so we need to always treat
      // them as attributes.
      // Note that `contentEditable` doesn't have this problem: its DOM
      // property is also enumerated string values.
      if (key === 'spellcheck' || key === 'draggable' || key === 'translate') {
          return false;
      }
      // #1787, #2840 form property on form elements is readonly and must be set as
      // attribute.
      if (key === 'form') {
          return false;
      }
      // #1526 <input list> must be set as attribute
      if (key === 'list' && el.tagName === 'INPUT') {
          return false;
      }
      // #2766 <textarea type> must be set as attribute
      if (key === 'type' && el.tagName === 'TEXTAREA') {
          return false;
      }
      // native onclick with string value, must be set as attribute
      if (nativeOnRE.test(key) && isString(value)) {
          return false;
      }
      return key in el;
  }

这里可以看到Vue对SVG/spellcheck/draggale/translate/form/input[list]/textarea[type]/onclick等做了特殊处理,要求返回false绑定数据到attribute上。

而我们自定义的属性只通过一行代码来判断,

return key in el;

如果elproperty上有key,则返回true,然后绑定数据到property上。

到此这篇关于Vue3属性绑定方法解析的文章就介绍到这了,更多相关Vue属性绑定内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 基于vue2实现上拉加载功能

    基于vue2实现上拉加载功能

    这篇文章主要为大家详细介绍了基于vue2实现上拉加载功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-11-11
  • vuex中使用modules时遇到的坑及问题

    vuex中使用modules时遇到的坑及问题

    这篇文章主要介绍了vuex中使用modules时遇到的坑及问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-08-08
  • 使用WebStorm导入已有Vue项目并运行的详细步骤与注意事项

    使用WebStorm导入已有Vue项目并运行的详细步骤与注意事项

    这篇文章主要介绍了如何使用WebStorm导入、运行和管理Vue项目,包括环境配置、Node.js和npm版本管理、项目依赖管理以及常见问题的解决方案,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2024-11-11
  • vue按需加载实例详解

    vue按需加载实例详解

    在本篇文章里小编给大家整理的是关于vue按需加载实例的相关知识点内容,有需要的朋友们可以学习参考下。
    2019-09-09
  • Vue3全局配置Axios并解决跨域请求问题示例详解

    Vue3全局配置Axios并解决跨域请求问题示例详解

    axios 是一个基于promise的HTTP库,支持promise所有的API,本文给大家介绍Vue3全局配置Axios并解决跨域请求问题,内容从axios部署开始到解决跨域问题,感兴趣的朋友一起看看吧
    2023-11-11
  • Vue中Quill富文本编辑器的使用教程

    Vue中Quill富文本编辑器的使用教程

    这篇文章主要介绍了Vue中Quill富文本编辑器的使用教程,包括自定义工具栏、自定义字体选项、图片拖拽上传、图片改变大小等使用方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-09-09
  • 详解vue模拟加载更多功能(数据追加)

    详解vue模拟加载更多功能(数据追加)

    本篇文章主要介绍了vue模拟加载更多功能(数据追加),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-06-06
  • vue中的.$mount(''#app'')手动挂载操作

    vue中的.$mount(''#app'')手动挂载操作

    这篇文章主要介绍了vue中.$mount('#app')手动挂载操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-09-09
  • vue使用数组splice方法失效,且总删除最后一项的问题及解决

    vue使用数组splice方法失效,且总删除最后一项的问题及解决

    这篇文章主要介绍了vue使用数组splice方法失效,且总删除最后一项的问题及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-09-09
  • Vue echarts封装组件需求分析与实现

    Vue echarts封装组件需求分析与实现

    在平常的项目中,echarts图表我们也是使用的非常多的,通常我们从后端拿到数据,需要在图表上动态的进行呈现,接下来我们就模拟从后端获取数据然后进行呈现的方法,这篇文章主要介绍了Vue echarts封装组件需求分析与实现
    2022-10-10

最新评论