0
点赞
收藏
分享

微信扫一扫

Vue--函数式组件--使用/教程/实例

蒸熟的土豆 2022-01-04 阅读 94

原文网址:Vue--函数式组件--使用/教程/实例_IT利刃出鞘的博客-CSDN博客

简介

说明

本文用示例介绍Vue中的函数式组件的用法。

官网

渲染函数 & JSX — Vue.js

什么是函数式组件

函数式组件实际上只是一个接受一些 prop 的函数。

函数式组件特点:

  1. 没有状态。
    1.  即:没有响应式数据
    2. 也不监听任何传递给它的状态。
  2. 没有实例。
    1.  即:没有 this 上下文
  3. 没有生命周期方法
  4. 只接收props参数 

函数式组件的优点

  1. 渲染的开销很小。(因为函数式组件只是函数)
  2. 便于包装组件。
    1.  例1:程序化地在多个组件中选择一个来代为渲染;
    2.  例2:在将 children、props、data 传递给子组件之前操作它们。

 用法

Vue.component('my-component', {
  functional: true,
  // Props 是可选的
  props: {
    // ...
  },
  // 为了弥补缺少的实例
  // 提供第二个参数作为上下文
  render: function (createElement, context) {
    // ...
  }
})

示例

<!doctype html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>this is title</title>
</head>

<body>

<div id="app">
    <list-view-comp :id="'listViewId'" :list-data="listData"></list-view-comp>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>Vue.config.productionTip = false</script>
<script>
    Vue.component('listViewComp', {
        functional: true,  // should be set true for functional component
        props: {
            listData : {type : Array, required : true}
        },
        render(createElement, context){
            console.log("title is: " + context.props.listData[0].title);
            console.log("content is: " + context.props.listData[0].content);
            let titleDom = createElement(
                "div",
                {
                    style : {
                        width : "450px",
                        height : "30px",
                        color : "red"
                    }
                },
                context.props.listData[0].title
            );
            let contentDom = createElement(
                "div",
                {
                    style : {
                        width : "450px",
                        height : "30px",
                        color : "green"
                    }
                },
                context.props.listData[0].content  // content is passed down by context
            );
            
            return createElement(
                "div",
                {
                    style : {
                        width: "1000px",
                        height: "300px"
                    }
                },
                [titleDom, contentDom] //The div have two children: titleDom, contentDom
            )
        }
    })

    const app = new Vue({
        data(){
            return{
                listData : [
                    {
                        title : "This is title",
                        content : "This is content"
                    }
                ]
            }
        }
    }).$mount("#app");
</script>

</body>
</html>

结果

   

举报

相关推荐

0 条评论