Vue 使用中的小技巧(6)
其中level是data中的变量,可以看到这里有大量重复代码,如果逻辑复杂点,加上一些绑定和判断就更复杂了,这里可以利用 render 函数来对要生成的标签加以判断。
2. 优化
使用 render 方法根据参数来生成对应标签可以避免上面的情况。
<template>
<div>
<child :level="level">Hello world!</child>
</div>
</template>
<script type='text/javascript'>
import Vue from 'vue'
Vue.component('child', {
render(h) {
const tag = ['div', 'p', 'strong', 'h1', 'h2', 'textarea'][this.level]
return h(tag, this.$slots.default)
},
props: {
level: { type: Number, required: true }
}
})
export default {
name: 'hehe',
data() { return { level: 3 } }
}
</script>
示例可以查看CodePen
8.2 动态组件
当然render函数还有很多用法,比如要使用动态组件,除了使用 :is 之外也可以使用render函数
<template>
<div>
<button @click='level = 0'>嘻嘻</button>
<button @click='level = 1'>哈哈</button>
<hr>
<child :level="level"></child>
</div>
</template>
<script type='text/javascript'>
import Vue from 'vue'
import Xixi from './Xixi'
import Haha from './Haha'
Vue.component('child', {
render(h) {
const tag = ['xixi', 'haha'][this.level]
return h(tag, this.$slots.default)
},
props: { level: { type: Number, required: true } },
components: { Xixi, Haha }
})
export default {
name: 'hehe',
data() { return { level: 0 } }
}
</script>
示例可以查看CodePen
总结
以上所述是小编给大家介绍的Vue 使用中的小技巧,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对黑区网络网站的支持!
