vue2之render+jsx从细节入手,彻底掌握
父组件 .vue
<template>
<div>
<myCom :msg="msg" :data-list="dataList" @on-change="comChange" />
</div>
</template>
<script>
import myCom from './renderTest/myCom.js'
export default {
components: {
myCom
},
data() {
return {
msg: '我是来自父组件的信息',
dataList: [
{
name: 'Json Brown',
age: '12',
address: 'asasasss',
date: '2023-12-12'
},
{
name: 'Json Brown',
age: '12',
address: 'asasasss',
date: '2023-12-12'
}
]
}
},
created() {
},
mounted() {
console.log(12)
},
methods: {
comChange(val) {
console.log('as', val)
}
}
}
</script>
render.js
import './style.scss' // 单独针对这个组件的样式
const ListItem = {
name: 'ListItem',
props: {
personList: Array
},
data() {
return {
userInfo: {
name: '诸葛亮',
age: '1000'
}
}
},
render(h) {
const { personList, userInfo } = this
return (
<div>
<ul class='list-view'>
{
personList.map((mp, index) => {
return (
<li class='li'>
<p class='tag-sort-view'>{index + 1}</p>
<p>姓名:{mp.name}</p>
<p>年龄:{mp.age}</p>
</li>
)
})
}
</ul>
{
this.$scopedSlots.header({ userInfo })
}
</div>
)
}
}
const SlotContent = {
props: {
userInfo: Object
},
render(h) {
const { userInfo } = this
console.log(userInfo)
return (
<div>
<div>这是插槽的</div>
{ userInfo.name}
{ userInfo.age}
</div>
)
}
}
export default {
name: 'myCom',
props: {
msg: String,
dataList: Array
},
data() {
return {
}
},
methods: {
handleClick(event, info) {
console.log(event, 12)
console.log(info)
this.$emit('on-change', info)
}
},
render(h) {
/**
* 解构之后,可以不用 this.
* const { msg, handleClick } = this
*/
const sSlots = {
header: (props) => <SlotContent userInfo={ props.userInfo }></SlotContent>
}
return (// 只能有一个根元素
<div>
<p onClick={ ($event) => this.handleClick($event, 'info') } class='bg' style={{ color: '#10ac84', margin: '20px', padding: '20px' }}>
我是嘿嘿
</p>
<h2 onClick={ this.handleClick }>
{this.msg}
</h2>
<ListItem personList={ this.dataList } scopedSlots={sSlots}></ListItem>
</div>
)
}
}