vue 動(dòng)態(tài)創(chuàng)建組件的兩種方法
import Vue from ’vue’/** * @param Component 組件實(shí)例的選項(xiàng)對(duì)象 * @param props 組件實(shí)例中的prop */export function create(Component, props) { const comp = new (Vue.extend(Component))({ propsData: props }).$mount() document.body.appendChild(comp.$el) comp.remove = () => { document.body.removeChild(comp.$el) comp.$destroy() } return comp}方式二
import Vue from ’vue’export function create(Component, props) { // 借雞生蛋new Vue({render() {}}),在render中把Component作為根組件 const vm = new Vue({ // h是createElement函數(shù),它可以返回虛擬dom render(h) { console.log(h(Component,{ props })); // 將Component作為根組件渲染出來(lái) // h(標(biāo)簽名稱(chēng)或組件配置對(duì)象,傳遞屬性、事件等,孩子元素) return h(Component, { props }) } }).$mount() // 掛載是為了把虛擬dom變成真實(shí)dom // 不掛載就沒(méi)有真實(shí)dom // 手動(dòng)追加至body // 掛載之后$el可以訪(fǎng)問(wèn)到真實(shí)dom document.body.appendChild(vm.$el) console.log(vm.$children); // 實(shí)例 const comp = vm.$children[0] // 淘汰機(jī)制 comp.remove = () => { // 刪除dom document.body.removeChild(vm.$el) // 銷(xiāo)毀組件 vm.$destroy() } // 返回Component組件實(shí)例 return comp}使用
A組件(要?jiǎng)討B(tài)創(chuàng)建的組件)
<template> <div class='a'> <h2>{{ title }}</h2> <p>{{ data }}</p> </div></template><script>export default { props: { title: { type: String, default: 'hello world!' }, message: { type: String, default: 'o(∩_∩)o 哈哈' }, duration: { type: Number, default: 1000 } }, data() { return { data: '我是a組件', }; }, created() { let num = 1 const timer = setInterval(() => { this.data = num++ }, this.duration) this.$once('hook: beforeDestroy', () => clearInterval(timer)) }};</script><style>.a { position: fixed; width: 100%; top: 16px; left: 0; text-align: center; pointer-events: none; background-color: #fff; border: grey 3px solid; box-sizing: border-box;}</style>
B組件(操作動(dòng)態(tài)創(chuàng)建組件的地方)
<template> <div class='b'> <button @click='createA'>創(chuàng)建</button> </div></template><script>import A from '@/components/A.vue'import { create } from '@/utils/create.js'export default { components: { A, }, methods: { createA() { // 創(chuàng)建A組件,并掛載到body上 create(A, { title: 'vue', message: '么么噠😙' }) } },};</script>
以上就是vue 動(dòng)態(tài)創(chuàng)建組件的兩種方法的詳細(xì)內(nèi)容,更多關(guān)于vue 動(dòng)態(tài)創(chuàng)建組件的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. PHP正則表達(dá)式函數(shù)preg_replace用法實(shí)例分析2. 一個(gè) 2 年 Android 開(kāi)發(fā)者的 18 條忠告3. vue使用moment如何將時(shí)間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時(shí)間格式4. js select支持手動(dòng)輸入功能實(shí)現(xiàn)代碼5. Android 實(shí)現(xiàn)徹底退出自己APP 并殺掉所有相關(guān)的進(jìn)程6. Android studio 解決logcat無(wú)過(guò)濾工具欄的操作7. 什么是Python變量作用域8. vue-drag-chart 拖動(dòng)/縮放圖表組件的實(shí)例代碼9. Spring的異常重試框架Spring Retry簡(jiǎn)單配置操作10. Vue實(shí)現(xiàn)仿iPhone懸浮球的示例代碼
