Vue 动态创建 component

发布时间:2019-05-07 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Vue 动态创建 component脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
小宝典致力于为广大程序猿(媛)提供高品质的代码服务,请大家多多光顾小站,小宝典在此谢过。

Vue 动态创建 component

Angular 中 可以通过 ComponentFactoryResolver 来动态创建 component , 在平时使用 vue过程中也没有了解到这方面的信息。于是就花时间研究了一下。

Vue 的组件可以通过两种方式来声明,一种是通过 Vue.COMponent,另外一种则是 Single File Components(Sfc

以下除非特别说明,组件都是全局注册的

Vue.component 方式

首先来看 Vue.component 方式的。

Vue.component('button-counter',{    data: function () {     return {       count: 0     }   },   template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>' });

在上面的代码中我们声明了一个叫做 button-counter 的组件。如果在常规情况下使用的话,只需要在页面上写对应的 <button-counter></button-counter> 标签就够了。

那么通过编程方式怎么处理呢?

官方文档中我们可以看到,我们可以通过 Vue.component('component-name') 的方式来获取到 组件。而组件实例又有 $mount 这样一个方法,官方对于 $mount 的解释如下:

$mount 方法有两个参数

  • {Element | string} [elementOrSelector]
  • {boolean} [hydrating]

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 上。

下面是完整的代码:

Vue.component("button-counter", {   data: function() {     return {       count: 0     };   },   template:     '<button v-on:click="count++">You clicked me {{ count }} times.</button>' });  Vue.component("app", {   data: function() {     return {       count: 0     };   },   template:     '<div> <h1>App Component</h1><button @click="insert">click to insert new Component</button> <div id="appId"> </div></div>',   methods: {     insert() {       const component = Vue.component("button-counter");       const instance = new component();       instance.$mount("#appId");     }   } });  new Vue({   el: "#app" }); 

https://codepen.io/YoRolling/...

SFC

在实际工作中,大部分都是用官方的脚手架 vue-cli 生成项目,用的也是 SFC 这种方式。

我们的 button-counter 如果用 SFC 方式实现的话应该是这样子的:

<template>     <button v-on:click="count++">You clicked me {{ count }} times.</button> </template>  <script> export default {   name: "ButtonCounter",   data() {     return {       count: 0     };   } }; </script>

那么是否可以通过 export 出的对象来实现我们的需求呢?

首先我们来看,在 SFC 中, 我们在 script 中 export 了一个对象出去,那么通过这个对象应该是可以达到要求的。

先来看看 import 之后这个对象是什么样子的。

Vue 动态创建 component

可以发现 import 得到的对象要比我们在 组件中声明的多了一些属性和方法。

Vue.component 模式中,我们先获取到组件的构造函数,然后构造实例,通过实例的一些方法来处理数据和挂载节点。

很显然,现有数据不能满足我们。如果我们能将这个对象转化成一个组件的构造函数,那我们就可以利用上面的方案来实现我们的需求了。

那么,究竟需要怎么转换呢?

没错! 就是 Vue.extend 这个大兄 dei!我们看下官方的说明。

Create a “subclass” of the base Vue constructor. The argument should be an object containing component options.

The sPEcial case to note here is the data option - it must be a function when used with Vue.extend().

通过传入一个包含 Component options 的对象, Vue.extend 帮助我们创建一个 继承了 Vue constructor 的子类,也就是我们之前需要的构造函数。

好了,得到了构造函数,接下来的工作就简单了 。实例化,然后挂载。

下面就是完整的代码:

<template>   <div id="app">     <div>     <img width="25%" src="./assets/LOGo.png">   </div>     <div>     <button @click="insert">click me to insert ButtonCounter</button>   </div>     <div id="container"></div>   </div> </template>  <script> import ButtonCounter From './components/ButtonCounter'; import Vue from 'vue'; export default {   name: 'App',   components: {     ButtonCounter,   },   methods: {     insert() {       const bcConstructor = Vue.extend(ButtonCounter);       const instance = new bcConstructor();       instance.$mount('#container');     },   }, }; </script>  <style> #app {   font-family: 'Avenir', Helvetica, Arial, sans-serif;   -webkit-font-smoothing: antialiased;   -moz-OSX-font-smoothing: grayscale;   text-align: center;   color: #2c3e50;   margin-top: 60px; } </style>    

在线查看 https://codesandbox.io/s/m59r3547zy

https://codesandbox.io/s/m59r...

结束

Happy Ending。

到这里,通过编程的方式动态创建组件挂载到HTML 的两种方式就完成了。

再次感到看文档的重要性。 🤨

👻 如有错误,欢迎大家斧正!

觉得可用,就经常来吧! 脚本宝典 欢迎评论哦!&nbsp;vue,巧夺天工,精雕玉琢。小宝典献丑了!

脚本宝典总结

以上是脚本宝典为你收集整理的Vue 动态创建 component全部内容,希望文章能够帮你解决Vue 动态创建 component所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。