[ vue ] 函數式組件中的class與style處理

引言:什麼是函數式組件

沒有管理任何狀態,也沒有監聽任何傳遞給它的狀態,也沒有生命週期方法。實際上,它只是一個接受一些 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中的staticClassstaticStyle對應DOM元素上的原生classstyle屬性。
context.data中的classstyle對應屬性DOM元素上綁定的v-bind:classv-bind:style

其中staticStyle爲什麼會轉換爲對象,是因爲Vue調了parseStyleText方法。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章