How to add dom to vuejs: 1. Create an instance with new first; 2. Manually mount it to the dom node; 3. Use "$appendTo/$before/$after" and other methods to interpolate.
The operating environment of this article: Windows7 system, Vue2.9.6 version, DELL G3 computer
How to add dom to vuejs?
How to use vue.js to insert dom nodes
This article mainly introduces the method of vue.js to insert dom nodes. I won’t say much below, let’s take a look. Let’s introduce it in detail.
html code:
<div id="app"></div>
js code:
var MyComponent = Vue.extend({ template: '<p>Hello World</p>' }) var myAppendTo = Vue.extend({ template:'<p>appendTo</p>' }) var myBefore = Vue.extend({ template:'<p>before</p>' }) var myAfter = Vue.extend({ template:'<p>after</p>' }) // 创建并挂载到 #app (会替换 #app) new MyComponent().$mount('#app'); // 手动挂载 new myAppendTo().$mount().$appendTo('#app');//appendTo new myBefore().$mount().$before('#app');//before new myAfter().$mount().$after('#app');//after
Description:
1. Comparing the insertion method of jquery's dom node, the interpolation of vue.js requires first creating an instance with new and then passing $mount()
.
2. Manually mount it to the dom node, and then use methods such as $appendTo
/$before
/$after
interpolation.
3. This idea of operating dom is actually not the way vue advocates, but the way vue advocates is to achieve the results you want by manipulating data.
4. The idea of vue is that the dom already exists, and you can control its display and hiding through judgment.
5. So when using vue, try to change the way you think when using jquery, like the method (v-if) provided by the api.
<ul> <li v-if="ok">显示</li> <li v-else>隐藏</li> </ul>
You can also control the display and hiding through (v-show):
<ul> <li v-show="ok">显示</li> </ul>
Then the difference between v-if and v-show:
When switching v-if blocks, Vue.js has a partial compilation/unloading process, because templates in v-if may also include data binding or subcomponents.
v-if is true conditional rendering, because it will ensure that the conditional block properly destroys and rebuilds the event listeners and subcomponents within the conditional block during the switch.
v-if is also lazy: if the condition is false on initial rendering, nothing is done - partial compilation starts only when the condition becomes true for the first time (compilation is cached stand up).
In comparison, v-show is much simpler - elements are always compiled and retained, and are simply toggled based on CSS.
Generally speaking, v-if has a higher switching cost and v-show has a higher initial rendering cost. Therefore, v-show is better if you need to switch frequently,
if conditions are unlikely to change at runtime, v-if is better.
Recommended: "The latest 5 vue.js video tutorial selections"
The above is the detailed content of How to add dom to vuejs. For more information, please follow other related articles on the PHP Chinese website!