Vue2渲染函数实战:5个高级组件开发技巧
1. 基础渲染函数
替代模板的渲染方式:
Vue.component('render-heading', {
props: ['level'],
render(createElement) {
return createElement(
'h' + this.level, // 标签名
this.$slots.default // 子节点数组
);
}
});
// 使用
<render-heading level="2">动态标题</render-heading>
Vue.component(‘render-heading’, {
props: [‘level’],
render(createElement) {
return createElement(
‘h’ + this.level,
this.$slots.default
);
}
});
new Vue({ el: ‘#app’ });
2. JSX语法应用
更直观的渲染函数写法:
Vue.component('jsx-button', {
props: ['type'],
render() {
return (
<button class={`btn btn-${this.type}`}>
{this.$slots.default}
</button>
);
}
});
// 需要配置Babel支持JSX
// babel.config.js:
// plugins: ["@vue/babel-plugin-transform-vue-jsx"]
3. 动态组件渲染
根据数据渲染不同组件:
const components = {
'text': {
render(h) {
return h('p', this.$slots.default);
}
},
'image': {
props: ['src'],
render(h) {
return h('img', { attrs: { src: this.src } });
}
}
};
Vue.component('dynamic-renderer', {
props: ['type', 'data'],
render(h) {
const component = components[this.type];
return h(component, {
props: this.data
}, this.$slots.default);
}
});
4. 高阶组件模式
增强现有组件功能:
function withLoading(WrappedComponent) {
return {
render(h) {
return h('div', [
h(WrappedComponent, {
props: this.$props,
on: this.$listeners
}),
this.isLoading ? h('div', '加载中...') : null
]);
},
data() {
return { isLoading: false }
},
methods: {
startLoading() { this.isLoading = true },
stopLoading() { this.isLoading = false }
}
};
}
// 使用
const EnhancedComponent = withLoading(MyComponent);
特性 | 模板语法 | 渲染函数 |
---|---|---|
灵活性 | 有限 | 极高 |
学习曲线 | 平缓 | 陡峭 |
适用场景 | 常规组件 | 动态/高阶组件 |
5. 电商实战:动态表单生成器
根据JSON配置渲染表单:
Vue.component('form-generator', {
props: ['schema'],
render(h) {
const fields = this.schema.map(field => {
const props = { ...field };
delete props.type;
return h(`form-${field.type}`, {
props,
on: {
input: value => this.$emit('update', field.name, value)
}
});
});
return h('form', fields);
}
});
// 使用
const schema = [
{ type: 'text', name: 'username', label: '用户名' },
{ type: 'select', name: 'gender', options: ['男','女'] }
];
<form-generator :schema="schema" @update="handleUpdate" />
Vue2渲染函数为复杂组件开发提供了强大工具,特别适合动态组件、高阶组件、JSX开发等需要灵活控制渲染逻辑的场景。