vue jsx
安装vue
cnpm i -g @vue/cli
cnpm i -g @vue/cli-service-global
创建基本文件
- main.js
import Vue from 'vue';
import App from './App';
new Vue({
el: '#app',
render: h => h(App)
})
- App.vue
<template>
<div>
<labelx :t="2">你好,中国</labelx>
</div>
</template>
<script>
import labelx from './component/label.js'
export default {
components: {
labelx
}
}
</script>
- label.js
export default {
props: {
t: {}
},
render() {
let tag = 'h' + this.t;
return (
<tag>{this.$slots.default}</tag>
)
}
}
jsx使用场景
动态标签,组件内部有可能是li,也有可能是span,实现插槽效果
<li></li>
<li></li>
<span></span>
<span></span>
- App.Vue
<template>
<div>
<list :data="['香蕉','苹果']" :render="render" />
</div>
</template>
<script>
import List from "./component/List";
export default {
components: {
List,
},
methods: {
render(h, item) {
return <span>{item}</span>
}
}
}
</script>
- List.vue
<template>
<div>
<template v-for="(item, index) in data">
<ListItem :render="render" :key="index" :item="item" />
</template>
</div>
</template>
<script>
import ListItem from "./ListItem";
export default {
props: {
data: {
type: Array,
default: () => []
},
render: {
type: Function
}
},
components: {
ListItem
}
}
</script>
- ListItem.js
export default {
props: {
render: {
type: Function,
},
item: {
type: String
}
},
render(h) {
return this.render(h, this.item)
}
}
插槽
- App.vue
<template>
<div>
<list :data="['香蕉','苹果']">
<template v-slot:cItem="{item}">
<li>{{item}}</li>
</template>
</list>
</div>
</template>
<script>
import List from "./component/List";
export default {
components: {
List,
},
methods: {
}
}
</script>
- List.vue
<template>
<div>
<template v-for="(item) in data">
<slot name="cItem" :item="item"></slot>
</template>
</div>
</template>
<script>
export default {
props: {
data: {
type: Array,
default: () => []
},
render: {
type: Function
}
},
components: {
}
}
</script>
父组件传递组件给子组件
- 使用插槽
- 父组件传递render方法给子组件