vue2中如何动态渲染组件

vue2 的项目中,main.js 文件中有一个挂载 App.vue 组件的方法:

new Vue({
   
  name: 'Root',
  render: h => h(App),
}).$mount('#app')

new Vue 创建了一个 Vue 实例,通过实例方法 $mount 方法将 App 组件挂载到 #app 上,这样就实现了App.vue 的渲染。

App.vue 渲染出来的模板会把 #app 替换掉。

App.vue 导出后是一个普通对象,没有 $mount 方法,而 Vue 实例有 $mount 方法。

问题:我们可以通过这样的方式动态地渲染一个组件吗?

答案是可以的。 通过 Vue.extend + $mount 动态挂载组件。

动态渲染组件

既然可动态渲染一个组件,把这个过程封装成一个函数,可通过函数调用的方式渲染组件。
下面的代码,当用户点击按钮时,会动态渲染一个 el-button 组件。

<script>
  import {
     
    Button
  } from 'element-ui'
  import Vue from 'vue'
  export default {
     
    name: 'DemoOne',
    methods: {
     
      showElButton() {
     
        const SubVue = Vue.extend(Button)
        const ButtonInstance = new SubVue({
     
          propsData: {
     
            type: 'primary'
          },
        })
        ButtonInstance.$slots = {
     
          default: 'el-button',
        }
        ButtonInstance.$mount(this.$refs.container)
      },
    },
  }
</script>
<template>
  <div>
    <h2>动态挂载组件</h2>
    <button @click="showElButton">显示el-button</button>
    <div>
      <div ref="container"></div>
    </div>
  </div>
</template>

代码解读

Vue.extend 是什么作用?

Vue.extend 接收一个组件对象,用于创建一个 Vue 的子类。 Vue.extend 返回的是一个 Vue 的子类,而不是一个 Vue 的实例。

new SubVue 是什么作用?

new SubVue 创建了一个 Button 组件的实例 ButtonInstance ,方便调用实例方法。

ButtonInstance. m o u n t ( t h i s . mount(this. mount(this.refs.container) 是什么作用?

ButtonInstance 挂载到 this.$refs.container 上,即将 el-button 渲染到页面上。
通过 Vue.extend$mount 方法,实现了动态地渲染组件。
了解了动态渲染组件的原理,我们可以通过函数调用的方式,动态地渲染组件。

通过函数调用渲染组件

上面的例子中 showElButton 方法局限了在组件内部,我们可以将这个方法抽离出来,挂载到 Vue 原型上,就可以在全局调用。

类似这样调用: this.$showElButton(params)

// showElButton.js
import {
   
  Button
} from 'element-ui'
import Vue from 'vue'

export function showElButton(target, {
   
  type = 'primary',
  label = 'el-button'
} = 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值