Method of inserting dom node by vue. js

  • 2021-08-03 09:17:31
  • OfStack

This article mainly introduces the method of inserting vue. js into dom node. Let's not say much below, let's take a look at the detailed introduction.

html code:


<div id="app"></div>

js code:


var MyComponent = Vue.extend({
 template: '<div>Hello World</div>'
})
var myAppendTo = Vue.extend({
template:'<p>appendTo</p>'
})
var myBefore = Vue.extend({
 template:'<p>before</p>'
})
var myAfter = Vue.extend({
 template:'<p>after</p>'
})
//  Create and mount to the  #app ( Will replace  #app)
new MyComponent().$mount('#app');

//  Manual mount 
new myAppendTo().$mount().$appendTo('#app');//appendTo
new myBefore().$mount().$before('#app');//before
new myAfter().$mount().$after('#app');//after

Description:

1. Compared with the insertion mode of dom node of jquery, the interpolation of vue. js needs to create an instance of new first and then pass $mount() .

2. Manually mount into the dom node and then use the $appendTo / $before / $after And other methods for interpolation.

3. This idea of manipulating dom is not actually the way advocated by vue, but the way advocated by vue is to manipulate data to achieve the desired results.

4. The idea of vue is that this dom already exists, and it can be controlled to show and hide by judgment.

5. So when using vue, try to change the thinking of using jquery under 1, just like the method provided by api (v-if).


<ul>
 <li v-if="ok"> Display </li>
 <li v-else> Hide </li>
</ul>

Display hiding can also be controlled through (v-show):


<ul>
 <li v-show="ok"> Display </li>
</ul>

Then the difference between v-if and v-show:

When switching v-if blocks, Vue. js has a local compile/unload process, because templates in v-if may also include data bindings or subcomponents.

v-if is true conditional rendering because it ensures that the conditional block properly destroys and reconstructs event listeners and subcomponents within the conditional block during switching.

v-if is also lazy: If the condition is false at initial rendering, nothing is done-local compilation begins when the condition becomes true for the first time (compilation is cached).

In contrast, v-show is much simpler--elements are always compiled and preserved, simply based on CSS switching.

1 In general, v-if has higher switching consumption and v-show has higher initial rendering consumption. Therefore, if you need to switch v-show frequently,
v-if is better if conditions are unlikely to change at run time.

Summarize


Related articles: