Home  >  Article  >  Web Front-end  >  A brief analysis of the difference between Ref operation Dom in Vue2.x and Vue3.x

A brief analysis of the difference between Ref operation Dom in Vue2.x and Vue3.x

青灯夜游
青灯夜游forward
2023-01-27 05:30:011929browse

Why is Ref operating Dom both easy to use and efficient? The following article will talk about Ref operation, introduce the essence of Ref obtaining Dom, its difference between Vue2.x and Vue3.x, etc. I hope it will be helpful to everyone!

A brief analysis of the difference between Ref operation Dom in Vue2.x and Vue3.x

Before developing a project, we often do a needs analysis first. For the front-end, we can research or choose a basic component library to improve our Work efficiency. After all, for a company that cares about time costs, it won't give you time to watch TV series and play games to develop a calendar-like component. However, not all component libraries on the market can meet our needs. At this time, we need to handwrite the components ourselves to apply them to the project.

And this is what I want to say: How to design components so that they are easy to apply (or reduce the amount of code), while also improving scalability and facilitating demand changes and subsequent maintenance?

There are many ways, and using Ref to operate Dom is one of them, but this method allows us to maintain and operate Modal, Popup, and frequently operate Dom display and When hiding interactive components, it plays a great advantage. [Related recommendations: vuejs video tutorial, web front-end development]

The relevant knowledge points and application examples of Ref operating Dom are divided into several aspects. Let’s do the analysis

  • Ref gets the essence of Dom
  • The difference between Ref operating Dom in Vue2.x and Vue3.x
  • Ref operating component Dom and parent-child component single Transfer comparison

Details

Ref gets the essence of Dom

Vue object in Vue2.x The attribute $refs is actually a collection of all registered refs, and ref corresponds to the ref="xx" associated with different components or ordinary Dom elements in the template; the actual way to obtain ref in the source code is also through the native method getElementById The obtained Dom node; can be said that ref is the syntactic sugar of document.getElementById. The ref of vue3 continues the usage of vue2, and also adds a function of creating responsive data

Some people may ask, since both ref and getElementById can get Dom, then in the project During development, does it make no difference which method I choose?

Regarding this issue, data shows that $refs will reduce the consumption of obtaining dom nodes compared to the document.getElementById method; the specific reasons will be discussed in detail in the next article.

The difference between Ref operation Dom in Vue2.x and Vue3.x

Vue2.x

We only need to add the ref="xx" attribute to the corresponding Dom element or component, and then use this.$refs.xx in the Vue object to directly obtain the Dom and operate its method attributes,

<user-and-dep-tree-select-modal
  ref="avaUserTreeSelect"
  title="選擇可見範圍"
  :project-id="currentProjectId"
  :visible.sync="avaUserModalVisible"
  @ok="editAvailableUser"
/>
或者
<div class="user" ref="user">dd</div>
// $refs
showManagerModal () {
  this.$refs.avaUserTreeSelect.showModal(this.form.managers)
  console.log(this.$refs.user.text)
},

Vue3.2

The method used in the Vue3.2 version

//普通Dom
<div class="user" ref="user"></div>
//组件
<batch-adjust-department-modal ref="batchAdjustDepartmentRef" />
<script setup>
import { ref } from &#39;vue&#39;;
// modal调整部门弹层Dom
const batchAdjustDepartmentRef = ref(null);
const user = ref(null);
</script>

Maybe someone here has questions about why a constant with the same name as the template's ref is declared Are variables bound to the corresponding DOM? Here’s a little additional explanation:

  • Vue3’s support for composition api in earlier versions (before 3.0.0-beta.21) can only be done in the component option setup function used in. The corresponding variables are all returned in the setup() method {write the variables or methods that need to be used in the template}
<script>
import { defineComponent, ref } from &#39;vue&#39;

export default defineComponent({
  name: &#39;HelloWorld&#39;,
  setup(props, ctx) {
    const count = ref(0)
    function add() {
      count.value++
    }
    // 使用return {} 把变量、方法暴露给模板
    return {
      count,
      add,
    }
  },
})
</script>
  • In version 3.0.0-beta.21 Added experimental features of 5101c0cdbdc49998c642c71f6b6410a8. If used, it will prompt that 5101c0cdbdc49998c642c71f6b6410a8 is still in the experimental feature stage.
  • Remove the experimental status of 5101c0cdbdc49998c642c71f6b6410a8 in version 3.2.0. From now on, it is announced that 5101c0cdbdc49998c642c71f6b6410a8 will be officially converted into regular use and become a stable framework. one of the characteristics of Compared with the component option setup function, 5101c0cdbdc49998c642c71f6b6410a8 we only need to write less and more concise code, and do not need to use return {} to expose variables And method, you don’t need to actively register when using the component, it will automatically bind for you

So the variables declared in5101c0cdbdc49998c642c71f6b6410a8 will be automatically added to The Vue object itself is in this, such as

##const user = ref(null);this.$ref.user

Ref操作组件Dom和父子组件单向传递

props父传子,子通过emits传父,这样单方向传递,在控制弹层组件的显示和隐藏方面也可以实现,但是如此一来,我们就会像下面一样 父组件

<template>
  <exchange-valid-modal-vue v-model:visible="visibleExchange" />
</template>
<script setup>
// 转让管理员组件
import ExchangeValidModalVue from &#39;./modal/ExchangeValidModal.vue&#39;;
// modal弹层
const visibleExchange = ref(false); // 转让管理员可视化
const onExchangeAdmin = () => {
  visibleExchange.value = true;
};
</script>

子组件ExchangeValidModalVue.vue

<template>
    <t-dialog
      v-model:visible="visibleExchange"
      header="转让主管理员"
      attach="body"
      width="384px"
      :confirm-on-enter="true"
      :on-close="onCloseExchange"
    />
</template>
<script setup>
const visibleExchange = ref(false);
const props = defineProps({
  data: {
    type: Object,
    default: () => {},
  },
  visible: {
    type: Boolean,
    default: false,
  },
});
watch(
  () => props.visible,
  (cur, pre) => {
    visibleExchange.value = cur;
    if (cur) {
      firstTag.value = 1;
    }
  },
);
watch(
  () => visibleExchange.value,
  (cur, pre) => {
    emits(&#39;update:visible&#39;, cur);
  },
);
</script>

从代码里面我们就可以发现通过用父子组件单向传递的方式去实现一个组件的显示和隐藏功能,我们需要如此费劲地声明多个变量,还要做两次监听,万一后面不止一个这样的参数进行传递,那么代码量可想而知,而且也不易维护。

其实显示和隐藏的功能可以直接在内部中进行值的响应即可,并不需要在父级别中操作,如下将上面代码改变一下:

子组件ExchangeValidModalVue.vue

<template>
    <t-dialog
      v-model:visible="visible"
      header="转让主管理员"
      attach="body"
      width="384px"
      :confirm-on-enter="true"
      :on-close="onCloseExchange"
    />
</template>
<script setup>
import { ref } from &#39;vue&#39;;
const visible = ref(false);
const emits = defineEmits([&#39;call&#39;]);
const onEmitSelectSuperiod = () => { // 省略
  emits(&#39;call&#39;);
};
const onOpen = () => {
  visible.value = true;
};
const onClose = () => {
  visible.value = false;
};

defineExpose({
  onOpen,
  onClose,
});
</script>

那么在父组件中,我们只需要通过ref得到该组件Dom,然后操作Dom内部的方法即可;

如:父组件改写

<template>
  <exchange-valid-modal-vue ref="exchangeRef" />
</template>
<script setup>
// 转让管理员组件
import ExchangeValidModalVue from &#39;./modal/ExchangeValidModal.vue&#39;;
// modal弹层
const exchangeRef = ref(null); // 转让管理员可视化
const onExchangeOpen = () => {
   exchangeRef.onOpen() // 直接操作dom里defineExpose暴露出来的方法
};
</script>

如此,是不是比父子单向数据传递的方式更加高效易用?当然上面所说的只是我举的一个例子,当后续需要在组件内扩展功能也可按类似的方法代替单向数据流的方式扩展

但,请注意;这种操作dom方式,并不是什么场景下都是最佳的选择;我们可以分情况选择,比如当一些数据只需要在子组件的范畴中实现,而不需要父组件外加干涉的情况下,选择ref操作dom更为高效;

补充知识点:

defineExpose

在 Vue3.2 中,默认不会暴露任何在 5101c0cdbdc49998c642c71f6b6410a8 中声明的绑定,即不能通过模板 ref 获取到组件实例声明的绑定。

Vue3.2 提供了 defineExpose 编译器宏,可以显式地暴露需要暴露的组件中声明的变量和方法

(学习视频分享:vuejs入门教程编程基础视频

## 5101c0cdbdc49998c642c71f6b6410a8 3f1c4e4b6b16bbbd69b2ee476dc4f83a

The above is the detailed content of A brief analysis of the difference between Ref operation Dom in Vue2.x and Vue3.x. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete