定義一個Title組件,在使用的時候,經過父組件傳值level去定義這個title是h1~h6vue
一、components/Title.vue:app
<template> <h1 v-if="level===1"> <a href=""> <slot></slot> </a> </h1> <h2 v-else-if="level===2"> <a href=""> <slot></slot> </a> </h2> <h3 v-else-if="level===3"> <a href=""> <slot></slot> </a> </h3> <h4 v-else-if="level===4"> <a href=""> <slot></slot> </a> </h4> <h5 v-else-if="level===5"> <a href=""> <slot></slot> </a> </h5> <h6 v-else-if="level===6"> <a href=""> <slot></slot> </a> </h6> </template> <script> export default { props: ['level'] } </script>
二、使用ide
<template> <div id="app"> <Title :level='1'>標題一</Title> <Title :level='2'>標題二</Title> <Title :level='3'>標題三</Title> <Title :level='4'>標題四</Title> <Title :level='5'>標題五</Title> <Title :level='6'>標題六</Title> </div> </template> <script> import Title from '@/components/Title' export default { components: { Title } } </script>
能夠發現,在定義Title組件時使用了大量的if、if-else,這裏可使用render進行渲染,代碼會變得簡潔this
components/title.js:spa
export default { props: ['level'], render(h) { const tag = 'h' + this.level return <tag><a href=''>{this.$slots.default}</a></tag> } }