国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

Vue動態創建注冊component的實例代碼

2024-05-06 15:38:01
字體:
來源:轉載
供稿:網友

前言

在深入了解Vue動態創建Component前先了解一下常規組件聲明形式。

Vue 的組件通??梢酝ㄟ^兩種方式來聲明,一種是通過 Vue.component,另外一種則是 Single File Components(SFC) 單文件組件 。

常規組件聲明與注冊

// 定義一個名為 button-counter 全局注冊的組件Vue.component("button-counter", { template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>', data() {  return {   count: 0  } }});new Vue({ template: `  <div id="app">   <h1>App Component</h1>   <button-counter></button-counter>  </div> `}).$mount("#app");

在上面的代碼中我們聲明了一個叫做 button-counter 的組件。如果在常規情況下使用的話,只需要在頁面上寫對應的 <button-counter></button-counter> 標簽就夠了。

全局創建注冊組件可以實現動態創建,但是我們必須在 template 聲明使用該組件,而且如果把所有組件都全局注冊這并不是一個好辦法。

在官方文檔中我們可以看到,我們可以通過 Vue.component('component-name') 的方式來注冊一個組件。

而組件實例又有 $mount 這樣一個方法,官方對于 $mount 的解釋如下:

vm.$mount( [elementOrSelector] )
Arguments:
{Element | string} [elementOrSelector]
{boolean} [hydrating]
Returns: vm - the instance itself
Usage:
If a Vue instance didn't receive the el option at instantiation, it will be in “unmounted” state, without an associated DOM element. vm.$mount() can be used to manually start the mounting of an unmounted Vue instance.
If elementOrSelector argument is not provided, the template will be rendered as an off-document element, and you will have to use native DOM API to insert it into the document yourself.
The method returns the instance itself so you can chain other instance methods after it.

那我們是否可以通過這種方式來達到我們的需求呢?

還不夠!

為什么???

因為 Vue.component 返回的結果是一個 function!它返回的并不是 組件實例,而是一個構造函數。

那到這里其實我們就清楚了。 對于 Vue.component 聲明的組件,我們先通過 Vue.component 獲取它的構造函數,再 new 出一個組件實例,最后 通過 $mount 掛載到 html 上。

// 定義一個名為 button-counter 全局注冊的組件Vue.component("button-counter", { template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>', data() {  return {   count: 0  } }});new Vue({ template: `  <div id="app">   <h1>App Component</h1>   <button @click="insert">click to insert button-counter comonent</button>   <div id="insert-container"></div>  </div> `, methods: {  insert() {   const ButtonCounter = Vue.component("button-counter"); // 只能查找到全局注冊到組件   const instance = new ButtonCounter();   instance.$mount("#insert-container");  } }}).$mount("#app");            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 故城县| 巫山县| 固原市| 手游| 垣曲县| 浏阳市| 墨竹工卡县| 博罗县| 中阳县| 竹溪县| 阜平县| 綦江县| 扎赉特旗| 于田县| 司法| 陇川县| 花莲市| 大悟县| 曲水县| 宜城市| 榆树市| 股票| 孝感市| 平武县| 咸宁市| 大关县| 含山县| 襄樊市| 施甸县| 涞水县| 华亭县| 延长县| 北辰区| 吉木乃县| 乌兰浩特市| 中宁县| 新兴县| 芦溪县| 福海县| 文成县| 松溪县|