首页 > 语言 > JavaScript > 正文

Vue函数式组件的应用实例详解

2024-05-06 15:35:14
字体:
来源:转载
供稿:网友

一、函数式组件和普通组件的区别

渲染快 没有实例,意味着没有(this) 没有生命周期(没有响应式数据)

二、组件函数的使用

  1.以局部组件为例,将组件标记为functional=ture;

因为函数式没有实例,因此组件需要的一切都是通过context参数传递,它是一个包括如下字段的对象:

props:提供所有 prop 的对象children: VNode 子节点的数组slots: 一个函数,返回了包含所有插槽的对象scopedSlots: (2.6.0+) 一个暴露传入的作用域插槽的对象。也以函数形式暴露普通插槽。data:传递给组件的整个数据对象,作为createElement的第二个参数传入组件parent:对父组件的引用listeners: (2.3.0+) 一个包含了所有父组件为当前组件注册的事件监听器的对象。这是data.on的一个别名。injections: (2.3.0+) 如果使用了inject选项,则该对象包含了应当被注入的属性。

在添加 functional: true 之后,需要更新我们的锚点标题组件的渲染函数,为其增加 context参数,并将 this.$slots.default 更新为 context.children,然后将 this.level 更新为 context.props.level。

因为函数式组件只是函数,所以渲染开销也低很多。

在作为包装组件时它们也同样非常有用。比如,当你需要做这些时:

程序化地在多个组件中选择一个来代为渲染; 在将 children、props、data 传递给子组件之前操作它们。
data() {    return {      changer:1    }  },
components: {    MyCmp:{      functional:true,  //必要的设置      render: function (createElement, context) {        function getcomp(cmp){          console.info(this); //输出为undefined,证明没有实例          if(cmp==1){            return comp1;           }else{            return comp2          }        }        return createElement(getcomp(context.props.changer),        {          props:{            cmpData:context.props.data //为子组件传递数据          }        }        );      },

 2. 定义要渲染的组件

var comp1={  props:['cmpData'],  render:function(createElement,context){    return createElement('el-input',{      props:{        type:this.cmpData      }    });  },  mounted() {    console.log(this) //这个组件为正常组件  },}var comp2={  props:['cmpData'],  render:function(createElement,context){    return createElement('el-button',{      props:{        type:this.cmpData      }    });  },  mounted() {    console.log(this) //正常组件  },}

三、在父组件中使用

<template>  <div>    <el-input v-model="changer" placeholder="子组件"></el-input>    <my-cmp :changer="changer"></my-cmp>  </div></template><script>            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选