亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home Web Front-end Front-end Q&A What does vue dom mean?

What does vue dom mean?

Dec 20, 2022 pm 08:41 PM
vue dom virtual dom

DOM is a document object model and an interface for HTML programming. Elements in the page are manipulated through DOM. The DOM is an in-memory object representation of an HTML document, and it provides a way to interact with web pages using JavaScript. The DOM is a hierarchy (or tree) of nodes with the document node as the root.

What does vue dom mean?

The operating environment of this tutorial: windows7 system, vue3 version, DELL G3 computer.

What is dom

dom is a document object model and an interface for HTML programming. The page is operated through dom Elements. When an HTML page is loaded, the browser creates a DOM, which provides a new logical structure to the document and can change the content and structure.

DOM is called the Document Object Model (DOM for short), which is a standard programming interface recommended by the W3C organization for processing extensible markup languages.

DOM is an in-memory object representation of an HTML document. It provides a way to interact with web pages using JavaScript. The DOM is a hierarchy (or tree) of nodes with the document node as the root.

In fact, DOM is a document model described in an object-oriented way. The DOM defines the objects required to represent and modify a document, the behaviors and properties of these objects, and the relationships between these objects.

Through JavaScript, we can reconstruct the entire HTML document. Such as adding, removing, changing or rearranging items on the page.

To change something on the page, JavaScript needs to gain access to all elements in the HTML document. This entry, along with the methods and properties for adding, moving, changing, or removing HTML elements, is obtained through the Document Object Model.

What is virtual DOM

I believe everyone is familiar with the concept of virtual DOM. From React to Vue, virtual DOM is Both frameworks bring cross-platform capabilities (React-Native and Weex)

In fact, it is just a layer of abstraction of the real DOM, with JavaScript objects (VNode nodes) as the base tree, using The attributes of the object are used to describe the nodes, and finally the tree can be mapped to the real environment through a series of operations

In the Javascript object, the virtual DOM is represented as an Object object. And it contains at least three attributes: tag name (tag), attributes (attrs) and child element objects (children). Different frameworks may have different names for these three attributes.

Creating a virtual DOM is just for better Render virtual nodes into the page view, so the nodes of the virtual DOM object correspond to the properties of the real DOM one by one.

Virtual DOM technology is also used in vue

Define the real DOM

<div id="app">
    <p class="p">節(jié)點內容</p>
    <h3>{{ foo }}</h3>
</div>

Instantiate vue

const app = new Vue({
    el:"#app",
    data:{
        foo:"foo"
    }
})

Observe the render of render, we can get the virtual DOM

(function anonymous(
) {
	with(this){return _c(&#39;div&#39;,{attrs:{"id":"app"}},[_c(&#39;p&#39;,{staticClass:"p"},
					  [_v("節(jié)點內容")]),_v(" "),_c(&#39;h3&#39;,[_v(_s(foo))])])}})

Through VNode, vue can create nodes, delete nodes and modify the abstract tree For node operations, some minimum units that need to be modified are obtained through the diff algorithm, and then the view is updated, which reduces DOM operations and improves performance.

Several methods for Vue to obtain DOM

Although Vue implements the MVVM model and separates data and performance, we only need to update The data can update the DOM synchronously, but in some cases, you still need to obtain DOM elements for operation (for example, a library introduced requires passing in a root dom element as the root node, or writing some custom instructions). This article mainly introduces Several ways to get DOM elements in Vue.

Use the DOM API to find elements directly

<script>
	...
	mounted () {
		let elm = this.$el.querySelector(&#39;#id&#39;)
	}
</script>

This method is simple and intuitive enough. The Vue component will This.$el is assigned the value of the mounted root dom element. We can directly use the $el's querySelector, querySelectorAll and other methods to obtain matching elements.

refs

<template>
	<div ref="bar">{{ foo }}</div>
	<MyAvatar ref="avatar" />
	...
</template>
<script>
	...
	mounted () {
		let foo = this.$refs[&#39;bar&#39;] // 一個dom元素
		let avatar = this.$refs[&#39;avatar&#39;] // 一個組件實例對象
	}
</script>

Use the $refs of the component instance to get the componentrefThe element corresponding to the attribute.
If the ref attribute is added to a component, then what you get is the instance of this component, otherwise what you get is the dom element.

It is worth noting that when the v-for loop template directive is included, the ref attribute on the loop element and sub-element corresponds to an array (even if it is dynamically generated ref, also an array):

<template>
	<div v-for="item in qlist" :key="item.id" ref="qitem">
		<h3>{{ item.title  }}</h3>
		<p ref="pinitem">{{ item.desc }}</p>
		<p :ref="&#39;contact&#39;+item.id">{{ item.contact }}</p>
	</div>
	...
</template>
<script>
	...
	data () {
		return {
			qlist: [
				{ id: 10032, title: &#39;abc&#39;, desc: &#39;aadfdcc&#39;, contact: 123 },
				{ id: 11031, title: &#39;def&#39;, desc: &#39;--*--&#39;, contact: 856 },
				{ id: 20332, title: &#39;ghi&#39;, desc: &#39;?/>,<{]&#39;, contact: 900 }
			]
		}
	},
	mounted () {
		let foo = this.$refs[&#39;qitem&#39;] // 一個包含dom元素的數組
		let ps = this.$refs[&#39;pinitem&#39;] // p元素是v-for的子元素,同樣是一個數組
		let contact1 = this.$refs[&#39;contact&#39; + this.qlist[0].id] // 還是個數組
	}
</script>

The reason for this can be obtained from Vue’s part of the code on ref processing:

function registerRef (vnode, isRemoval) {
  var key = vnode.data.ref;
  if (!isDef(key)) { return }

  var vm = vnode.context;
  // vnode如果有componentInstance表明是一個組件vnode,它的componentInstance屬性是其真實的根元素vm
  // vnode如果沒有componentInstance則不是組件vnode,是實際元素vnode,直接取其根元素
  var ref = vnode.componentInstance || vnode.elm;
  var refs = vm.$refs;
  if (isRemoval) {
    ...
  } else {
  	// refInFor是模板編譯階段生成的,它是一個布爾值,為true表明此vnode在v-for中
    if (vnode.data.refInFor) {
      if (!Array.isArray(refs[key])) {
        refs[key] = [ref]; // 就算元素唯一,也會被處理成數組
      } else if (refs[key].indexOf(ref) < 0) {
        // $flow-disable-line
        refs[key].push(ref);
      }
    } else {
      refs[key] = ref;
    }
  }
}

Use custom instructions

Vue provides custom instructions. The official documentation gives the following usage methods, where el is the reference to the dom element

Vue.directive(&#39;focus&#39;, {
  // 當被綁定的元素插入到 DOM 中時……
  inserted: function (el) {
    // 聚焦元素
    el.focus()
  }
})

// 在模板中
<template>
	<input v-model="name" v-focus />
</template>

Regarding custom instructions, It is very useful in scenarios such as component libraries and event reporting.

[Related recommendations: vuejs video tutorial, web front-end development]

The above is the detailed content of What does vue dom mean?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the significance of Vue's reactivity transform (experimental, then removed) and its goals? What is the significance of Vue's reactivity transform (experimental, then removed) and its goals? Jun 20, 2025 am 01:01 AM

ReactivitytransforminVue3aimedtosimplifyhandlingreactivedatabyautomaticallytrackingandmanagingreactivitywithoutrequiringmanualref()or.valueusage.Itsoughttoreduceboilerplateandimprovecodereadabilitybytreatingvariableslikeletandconstasautomaticallyreac

How can internationalization (i18n) and localization (l10n) be implemented in a Vue application? How can internationalization (i18n) and localization (l10n) be implemented in a Vue application? Jun 20, 2025 am 01:00 AM

InternationalizationandlocalizationinVueappsareprimarilyhandledusingtheVueI18nplugin.1.Installvue-i18nvianpmoryarn.2.CreatelocaleJSONfiles(e.g.,en.json,es.json)fortranslationmessages.3.Setupthei18ninstanceinmain.jswithlocaleconfigurationandmessagefil

How can you optimize the re-rendering of large lists or complex components in Vue? How can you optimize the re-rendering of large lists or complex components in Vue? Jun 07, 2025 am 12:14 AM

Methods to optimize the performance of large lists and complex components in Vue include: 1. Use the v-once directive to process static content to reduce unnecessary updates; 2. implement virtual scrolling and render only the content of the visual area, such as using the vue-virtual-scroller library; 3. Cache components through keep-alive or v-once to avoid duplicate mounts; 4. Use computed properties and listeners to optimize responsive logic to reduce the re-rendering range; 5. Follow best practices, such as using unique keys in v-for, avoiding inline functions in templates, and using performance analysis tools to locate bottlenecks. These strategies can effectively improve application fluency.

What are the benefits of using key attributes (:key) with v-for directives in Vue? What are the benefits of using key attributes (:key) with v-for directives in Vue? Jun 08, 2025 am 12:14 AM

Usingthe:keyattributewithv-forinVueisessentialforperformanceandcorrectbehavior.First,ithelpsVuetrackeachelementefficientlybyenablingthevirtualDOMdiffingalgorithmtoidentifyandupdateonlywhat’snecessary.Second,itpreservescomponentstateinsideloops,ensuri

What is server side rendering SSR in Vue? What is server side rendering SSR in Vue? Jun 25, 2025 am 12:49 AM

Server-siderendering(SSR)inVueimprovesperformanceandSEObygeneratingHTMLontheserver.1.TheserverrunsVueappcodeandgeneratesHTMLbasedonthecurrentroute.2.ThatHTMLissenttothebrowserimmediately.3.Vuehydratesthepage,attachingeventlistenerstomakeitinteractive

How to implement transitions and animations in Vue? How to implement transitions and animations in Vue? Jun 24, 2025 pm 02:17 PM

ToaddtransitionsandanimationsinVue,usebuilt-incomponentslikeand,applyCSSclasses,leveragetransitionhooksforcontrol,andoptimizeperformance.1.WrapelementswithandapplyCSStransitionclasseslikev-enter-activeforbasicfadeorslideeffects.2.Useforanimatingdynam

What is the purpose of the nextTick function in Vue, and when is it necessary? What is the purpose of the nextTick function in Vue, and when is it necessary? Jun 19, 2025 am 12:58 AM

nextTick is used in Vue to execute code after DOM update. When the data changes, Vue will not update the DOM immediately, but will put it in the queue and process it in the next event loop "tick". Therefore, if you need to access or operate the updated DOM, nextTick should be used; common scenarios include: accessing the updated DOM content, collaborating with third-party libraries that rely on the DOM state, and calculating based on the element size; its usage includes calling this.$nextTick as a component method, using it alone after import, and combining async/await; precautions include: avoiding excessive use, in most cases, no manual triggering is required, and a nextTick can capture multiple updates at a time.

How can environment variables be managed and accessed within a Vue application? How can environment variables be managed and accessed within a Vue application? Jun 14, 2025 am 12:22 AM

Managing environment variables in Vue applications requires specific rules and using .env files. First, only variables prefixed with VUE_APP_ will be exposed to the application; second, different environments correspond to different .env files, such as .env.development, .env.production, etc.; third, variables are injected during construction and cannot be changed at runtime. The specific steps include: 1. Create .env files in the project root directory; 2. Use the corresponding .env files according to the pattern, such as .env.staging; 3. Access variables through process.env in the code; 4. You can import the variables into config.js for unified management; 5. If you need multiple environments to support, you can use package

See all articles