转 http://www.furthersense.com/docs/vuejs/vue_jsx
拆分render函数
const Demo = {
data: () => ({
message: 'world'
}),
render(h) {
const { message } = this;
return (
<div class="demo">
Hello <span>{ message }</span>
</div>
)
}
}
// 可以拆分为
const _span = function (text) {
const h = this.$createElement; // 声明不可省略
return (
<span>{text}</span>
)
}
const Demo = {
data: () => ({
message: 'world'
}),
methods: {
_span
},
render(h) {
const { message, _span } = this;
return (
<div class="demo">
Hello { _span(message) }
</div>
)
}
}
语义化的组件封装
import { mapState, mapMutations } from 'vuex'
const store = new Vuex.Store({
state: {
theme: 'light'
},
mutations: {
setTheme(state, theme) {
state.theme = theme;
}
},
}) // store里保存了全局的主题
const Themed = {
computed: {
...mapState(['theme'])
},
methods: {
...mapMutations(['setTheme'])
},
}
Themed.div = {
extends: Themed,
render() {
return (
<div class={this.theme}>
{this.$slots.default}
</div>
)
},
}
Themed.switcher = {
extends: Themed,
render() {
return (
<button on-click={ () => this.setTheme(this.theme === 'light' ? 'dark' : 'light') }>切换主题</button>
)
}
}
export default {
render(h) {
return (
<div class="test">
<Themed.switcher />
<Themed.div>
<span>主题</span>
</Themed.div>
</div>
)
}
}