說(shuō)說(shuō) Vue.js 中的 functional 函數(shù)化組件

Vue.js 組件提供了一個(gè) functional 開(kāi)關(guān),設(shè)置為 true 后,就可以讓組件變?yōu)闊o(wú)狀態(tài)、無(wú)實(shí)例的函數(shù)化組件。因?yàn)橹皇呛瘮?shù),所以渲染的開(kāi)銷相對(duì)來(lái)說(shuō),較小。

函數(shù)化的組件中的 Render 函數(shù),提供了第二個(gè)參數(shù) context 作為上下文,data、props、slots、children 以及 parent 都可以通過(guò) context 來(lái)訪問(wèn)。

1 示例

這里,我們用 functional 函數(shù)化組件來(lái)實(shí)現(xiàn)一個(gè)智能組件。

html:

<div id="app">
    <smart-component :data="data"></smart-component>
    <button @click="change('img')">圖片組件</button>
    <button @click="change('video')">視頻組件</button>
    <button @click="change('text')">文本組件</button>
</div>

js:

//圖片組件設(shè)置
var imgOptions = {
    props: ['data'],
    render: function (createElement) {
        return createElement('div', [
            createElement('p', '圖片組件'),
            createElement('img', {
                attrs: {
                    src: this.data.url,
                    height: 300,
                    weight: 400

                }
            })
        ]);
    }
};

//視頻組件設(shè)置
var videoOptions = {
    props: ['data'],
    render: function (createElement) {
        return createElement('div', [
            createElement('p', '視頻組件'),
            createElement('video', {
                attrs: {
                    src: this.data.url,
                    controls: 'controls',
                    autoplay: 'autoplay'
                }
            })
        ]);
    }
};

//文本組件設(shè)置
var textOptions = {
    props: ['data'],
    render: function (createElement) {
        return createElement('div', [
            createElement('p', '文本組件'),
            createElement('p', this.data.content)
        ]);
    }
};

Vue.component('smart-component', {
    //設(shè)置為函數(shù)化組件
    functional: true,
    render: function (createElement, context) {
        function get() {
            var data = context.props.data;

            console.log("smart-component/type:" + data.type);
            //判斷是哪一種類型的組件
            switch (data.type) {
                case 'img':
                    return imgOptions;
                case 'video':
                    return videoOptions;
                case 'text':
                    return textOptions;
                default:
                    console.log("data 類型不合法:" + data.type);
            }
        }

        return createElement(
            get(),
            {
                props: {
                    data: context.props.data
                }
            },
            context.children
        )
    },
    props: {
        data: {
            type: Object,
            required: true
        }
    }
})

var app = new Vue({
    el: '#app',
    data: {
        data: {}
    },
    methods: {
        change: function (type) {
            console.log("輸入類型:" + type);
            switch (type) {
                case 'img':
                    this.data = {
                        type: 'img',
                        url: 'http://pic-bucket.ws.126.net/photo/0001/2019-02-07/E7D8PON900AO0001NOS.jpg'
                    }
                    break;
                case 'video':
                    this.data = {
                        type: 'video',
                        url: 'http://wxapp.cp31.ott.cibntv.net/6773887A7F94A71DF718E212C/03002002005B836E73A0C5708529E09C1952A1-1FCF-4289-875D-AEE23D77530D.mp4?ccode=0517&duration=393&expire=18000&psid=bbd36054f9dd2b21efc4121e320f05a0&ups_client_netip=65600b48&ups_ts=1549519607&ups_userid=21780671&utid=eWrCEmi2cFsCAWoLI41wnWhW&vid=XMzc5OTM0OTAyMA&vkey=A1b479ba34ca90bcc61e3d6c3b2da5a8e&iv=1&sp='
                    }
                    break;
                case 'text':
                    this.data = {
                        type: 'text',
                        content: '《流浪地球》中的科學(xué):太陽(yáng)何時(shí)吞并地球?科學(xué)家已經(jīng)給出時(shí)間表'
                    }
                    break;
                default:
                    console.log("data 類型不合法:" + type);
            }

        }
    },
    created: function () {
        //默認(rèn)為圖片組件
        this.change('img');
    }

});

效果:

  • 首先定義了圖片組件設(shè)置對(duì)象、視頻組件設(shè)置對(duì)象以及文本組件設(shè)置對(duì)象,它們都以 data 作為入?yún)ⅰ?/li>
  • 函數(shù)化組件 smart-component,也以 data 作為入?yún)?。?nèi)部根據(jù) get() 函數(shù)來(lái)判斷需要渲染的組件類型。
  • 函數(shù)化組件 smart-component 的 render 函數(shù),以 get() 作為第一個(gè)參數(shù);以 smart-component 所傳入的 data,作為第二個(gè)參數(shù):
return createElement(
    get(),
    {
        props: {
            data: context.props.data
        }
    },
    context.children
)
  • 根實(shí)例 app 的 change 方法,根據(jù)輸入的類型,來(lái)切換不同的組件所需要的數(shù)據(jù)。

2 應(yīng)用場(chǎng)景

函數(shù)化組件不常用,它應(yīng)該應(yīng)用于以下場(chǎng)景:

  • 需要通過(guò)編程實(shí)現(xiàn)在多種組件中選擇一種。
  • children、props 或者 data 在傳遞給子組件之前,處理它們。

本文示例代碼

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容