引言:什麼是函數式組件
沒有管理任何狀態,也沒有監聽任何傳遞給它的狀態,也沒有生命週期方法。實際上,它只是一個接受一些 prop 的函數。在這樣的場景下,我們可以將組件標記爲 functional,這意味它無狀態 (沒有響應式數據),也沒有實例 (沒有 this 上下文)。
一個函數式組件就像這樣:
Vue.component('my-component', {
functional: true,
// Props 是可選的
props: {
// ...
},
// 爲了彌補缺少的實例
// 提供第二個參數作爲上下文
render: function (createElement, context) {
// ...
}
})
1. 函數式組件的class和style的數據在哪裏?
在context
對象的data
屬性中。
2. class和style的數據在context.data
中是如何表現的?
它們以一下形式進行表現。
staticClass?: string;
class?: any;
staticStyle?: { [key: string]: any };
style?: string | object[] | object;
3. staticClass和class、staticStyle和style的使用場景
我們在使用組件的時候class屬性和style屬性有以下使用情況。
<my-component
class="my-component"
:class="{'active':true}"
style="width:100%;"
:style="{height: '200px'}" >
</my-component>
此時context.data
內的數據如下:
{
staticClass: "my-component",
class: {active: true},
staticStyle: {width: "100%"},
style: {height: "200px"}
}
從上面可以發現:
context.data
中的staticClass
、staticStyle
對應DOM元素上的原生class
、style
屬性。
context.data
中的class
、style
對應屬性DOM元素上綁定的v-bind:class
、v-bind:style
。
其中staticStyle
爲什麼會轉換爲對象,是因爲Vue調了parseStyleText方法。