1.前言
vue其實也有函數(shù)式組件哦,不是react才有函數(shù)組件的
這篇文章之前,建議先看下渲染函數(shù)標(biāo)題組件,有銜接關(guān)系
2.函數(shù)組件概念也都一樣
組件沒有管理任何狀態(tài),也沒有監(jiān)聽任何傳遞給它的狀態(tài),也沒有生命周期訪問
優(yōu)點就是 輕量,靈活
簡單翻譯 既沒有 data, 也沒有 this
2.函數(shù)式組件寫法
2.1 標(biāo)志是functional
functional:true, //函數(shù)組件
2.2 沒有this的影響
- 沒有
template了,寫上也不生效- 所有屬性通過
render的第二個參數(shù)conetxt傳遞
簡單的說就是把用到this獲取屬性的地方 ,屬性都從context的props解構(gòu)出來
在這篇文章渲染函數(shù)標(biāo)題組件,基礎(chǔ)上進(jìn)行修改
3.貼圖比較

1.png
4. 上代碼
效果和之前的是一樣的
Vue.component("heading", {
functional:true, //函數(shù)組件
props: {
level: {
type: String,
default: "1"
},
title: {
type: String,
default: ""
},
icon: {
type: String
}
},
render(h,context) {
// 子節(jié)點數(shù)組
console.log("上下文:",context);
let children = []
// 屬性獲取的變化
const {icon,title,level} = context.props
// icon處理
if (icon) {
children.push(h(
"svg",
{ class: "icon" },
[h("use", {
attrs: { 'xlink:href': '#icon-' +icon }
})]
))
}
children = children.concat(context.children)
const vnode = h(
"h" + level,
{ attrs: { title } },
children
)
console.log("查看", vnode);
return vnode
}
})