vue中使用jsx
為什么需要使用jsx呢?這個需要搞清楚
其實vue官方也說了,對於那些非常多v-if v-else的情況,就可以嘗試使用render函數或者jsx,不過render函數寫簡單的結構還行,結構復雜了就很蛋疼了,而既然用到render了,肯定是有一些復雜的邏輯判斷,結構肯定簡單不了,所以用jsx就是一個比較好的選擇了
今天自己嘗試了一下,也是借鑒了網上的一些例子,不過在使用圖片的時候發現事情好像有點難搞
<script>
import img_more from '../assets/images/pk/icon-more.png';
export default {
name: 'More',
props: {
type: {
required: true
}
},
data() {
return {
text: 'xxxxxxxjsx',
role: 1
}
},
render() {
return (
<div
class={{
btn: true,
'btn-success': this.type === 'success',
'btn-danger': this.type === 'danger',
'btn-warning': this.type === 'warning'
}}
>
{this.text}
/*這種寫法是可以的,圖片路徑通過變量傳遞進來,此時可以顯示圖片*/
<img class={{more: true}} onClick={this.handleClick} src={img_more} alt="" />
/* 這種寫法,直接寫圖片相對路徑,無法顯示圖片 是不是很蛋疼,(暫時還不知道針對圖片的具體規則)*/
<img src="../assets/images/pk/icon-more.png" alt="" />
</div>
);
},
methods: {
handleClick() {
console.log('點擊了', this.role);
}
}
}
</script>
<style scoped lang="scss">
.more{
width: 36px;
height: 36px; //設置背景圖片也是可以正常顯示圖片的
/*background: url("../assets/images/pk/icon-more.png") no-repeat;*/
/*-webkit-background-size: 100%;*/
/*background-size: 100%;*/
}
.btn{
width: 100px;
height: 50px;
&.btn-success{
background-color: yellowgreen;
}
}
</style>
從上面的代碼中可以學習的有
- class的寫法,包含已知的class以及根據變量來動態添加的
- 事件的添加
這個組件自己還只是開了個頭,里面的邏輯還沒有嘗試,待我寫完了在來把本文寫完