vue使用render渲染&jsx

时间:2024-01-17 13:48:26

vue&jsx文档

vue实例属性

// App.ts
import hBtn from './components/hBtn'
import hUl from './components/hUl' export default {
data(){
return {
theme: "mdui-theme-pink",
accent: "mdui-theme-accent-pink",
users:['aoo', 'boo', 'coo']
}
},
methods:{ },
render(h){
return h('div',{
'class':[this.theme, this.accent],
attrs:{
id: 'app'
}
},[
h(hBtn,{
'class':['mdui-color-theme-accent']
}),
h('ul',{},
[
h('li',{
'class':{
'text-danger':true
},
style:{
color:'red';
}
} ,'start'),
this.users.length
? this.users.map((key, index)=>{
return h('li',key)
})
: h('li','v-if else 这样写')
,
h('li', 'end')
]
),
h(hUl,{
attrs:{
users:['user1', 'user2']
}
})
]);// return end
}, //render end
}

// src/components/hBtn.ts

var Text = {// 在内部定义了一个组件
props:['body'],
render(h){
return h('span',[this.body])
}
} export default {
data(){
return {
myName: "ajanuw"
}
},
methods:{
echo (num:number):void {
alert(num)
}
},
mounted(){
console.log( '组件渲染完成!!')
},
render(h) {
return h(
'button',
{
// 和`v-bind:class`一样的 API
'class':['mdui-btn'],
style: {// 定义 style
fontSize: '22px'
},
attrs:{// 定义attribute, 可以利用这个更组件传递 props
id: "ajanuw"
},
domProps: {// DOM 属性
// innerHTML 会替换组件内部的赋值
},
on: {
click: this.echo.bind(null, 1995)
}
},
[
h(Text, {attrs:{body:"this a "},ref: 'start'} ),
h(Text, {attrs:{// 使用text组件, 传递props
body:this.myName}, ref: 'end'} )
]
);
}
}

// src/components/hUl.ts
// 渲染一个列表 var list = {
props:['body']
render(h){
return h('li', this.body)
}
}; export default {
props:['users'],
render(h){
if(this.users){
if(this.users.length){
return h('ul',{},[
this.users.map((key, index)=>{
return h(list,{
attrs:{
body: key
}
})
})
])
}else{
return h('ul', {}, [
return h(list, {
attrs:{
body: "没有数据哦!"
}
})
])
}
} }, //render end
}

下面是jsx

vue init webpack vueJsx

cd vueJsx

npm install babel-plugin-syntax-jsx babel-plugin-transform-vue-jsx babel-helper-vue-jsx-merge-props babel-preset-env --save-dev

npm i

npm start

// .babelirc

{
"presets": ["env"],
"plugins": ["transform-vue-jsx"]
}

// App.js

var Text = {
props:['body'],
render(h){
return(
<p
onClick={ ()=> console.log( this.body)}
style={{color:'red'}}
>
hello {this.body}
</p>
);// return end
}
}
var List = {
props:['body'],
render(h){
return (
<li onClick={()=> console.log( this.body)}>{ this.body}</li>
);
}
} export default {
data(){
return {
name:"ajanuw",
users: ['aoo', 'boo']
}
},
methods:{
echo(name){
alert( name)
}
},
render(h){
return (
<div id="app">
<Text body={this.name}/>
<ul>
{
this.users.length !==0
? this.users.map((key, index)=>{
return <List body={key} key={index}/>
})
: <li>没有数据</li>
}
</ul>
</div>
);// return end
}, // render end
}

"vue": "^2.5.2" 发现自带 jsx 模块。。。

把App.vue 改成 App.js 文件

// App.js
export default {
data(){
return {
name: 'ajanuw'
}
}, render(){
return (
<div id="app">
<p>hello {this.name}</p>
</div>
)
}
}
// main.js
import App from './App' => import App from './App.js'