当我们使用
Vue或React时,往往会将页面拆分为各种组件,通过拼装组件来形成页面和应用,就像搭积木一样。
那么,大家有没有思考过:“组件的产出是什么?”
# 组件的产出是什么
在 JQuery 盛行的年代,比起组件,“模板引擎”的概念要更加流行。
我们可以使用 lodash.template 函数来回忆一下当年是如何用模板开发一个页面的:
import { template } from 'lodash'
const compiler = template('<h1><%= title %></h1>')
const html = compiler({ title: 'My Component' })
document.getElementById('app').innerHTML = html
@前端进阶之旅: 代码已经复制到剪贴板
模板引擎的概念是:字符串 + 数据 => html。
lodash.template 函数虽然称不上是“引擎”,但足以说明问题。
我们将模板字符串传递给 template 函数,该函数返回一个编译器 compiler,只要把数据传入 compiler 函数,便能得到最终想要渲染的内容。
当数据发生变化时,我们需要使用新的数据重新编译模板:
const newHtml = compiler({ title: 'New Component' })
@前端进阶之旅: 代码已经复制到剪贴板
如果把上面的逻辑封装成一个函数,那么一个组件就诞生了:
const MyComponent = props => {
const compiler = MyComponent.cache || (MyComponent.cache = template('<h1><%= title %></h1>'))
return compiler(props)
}
MyComponent.cache = null
@前端进阶之旅: 代码已经复制到剪贴板
我们可以这样使用它:
