創建
index.js
import "./index.less" //{0}
export default {
name: 'testComp',
props: {
title:""
},
data() {
return {
name:'test'
}
},
computed:{},
created() {},
..., //{1}
methods: {
test(){
console.log("testFn")
}
},
render() { //{2}
console.log(this.title);
console.log(this.name);
this.test();
return (
<div>
函式式組件
</div>
)
},
}
{0} :這個是引入的css
{1}:這里省略掉其他的內容
{2}:只里有一個
render函式,這個函式類似普通組件的template,但是比template做的事多頁面效果:

總結:
其實函式式組件和普通組件沒有很大的區別,主要通過
render函式回傳頁面顯示內容,而render函式是可以通過this呼叫到所有內容的
index.less
div{
color: red;
}
app.vue
<test-comp title="測驗組件"></test-comp>
基礎開發
還是和以前組件一樣正常開發就是了,只是說
HTML部分通過函式回傳,下面撰寫幾種常用的回傳方式
簡單函式回傳
methods上添加方法simpleReturn
simpleReturn() {
return (<span class='test'>這是一種簡單回傳</span>)
}
render函式上呼叫該方法
render() {
return (
<div>
函式式組件{this.simpleReturn()}
</div>
)
},
index.less上添加樣式test
div{
color: red;
}
.test{
color: blue;
}
展示效果

基本語法: 這里你可以看到我們不再使用
template上的{{}},而是{}表示js相關代碼還有這里用的還是class,在react上是className,不要混了哦!
if判斷回傳
methods上添加方法ifReturn
ifReturn(bol) {
let content = null;
if(bol){
content = <p class='test'>我是true的回傳</p>;
}else{
content = <p class='test'>我是false的回傳</p>;
}
return content
}
render函式上呼叫該方法
render() {
return (
<div>
函式式組件{this.simpleReturn()}
{this.ifReturn(false)}
{this.ifReturn(true)}
</div>
)
},
展示效果

for回圈回傳
methods上添加方法forReturn
forReturn(arr) {
let content = [];
for (let index = 0; index < arr.length; index++) {
content.push(<li>{arr[index]} : {index}</li>)
}
return content
}
render函式上呼叫該方法
render() {
return (
<div>
// 因為關注點問題,我省略了前面的代碼!!! 后面貼全部
<ul>
{this.forReturn(["測驗","哈哈","嘻嘻","哇哇"])}
</ul>
<ul>
{["測驗","哈哈","嘻嘻","哇哇"].map((item,index) => <li>{index}:{item}</li>)}
</ul>
</div>
)
},
展示效果

這里有兩種方式實作回圈,其實基本一樣,但是代碼分離可能對后面的維護更方便,注意這里使用的是陣列的
map方法,不知道的可以查查資料
屬性系結(中階)
如果說這個不能系結屬性,那再怎么說都不香了,其實我們看到這里的所有
js部分都是由{}完成的,所以我們大膽猜測一下,屬性系結是不是也是這樣呢???
render函式
render() {
return (
<div>
// 因為關注點問題,我省略了前面的代碼!!! 后面貼全部
<input v-model={name}/>
</div>
)
},
效果

咦,
test沒上去,這個系結咋不靈了,難道我們猜錯了,不會吧,不會吧,不會真的錯了吧!!!思考:我們在哪寫的代碼???
回答:
render函式呀!!!注意:對,
render函式,你以前在函式中使用是直接用的name屬性的嗎???是不是明白了什么,以前能在
template上使用不需要this,但是現在要了!!!
所以最后修改為
render() {
return (
<div>
// 因為關注點問題,我省略了前面的代碼!!! 后面貼全部
<input v-model={this.name}/>
<input value=https://www.cnblogs.com/wangzhaoyv/archive/2020/11/25/{this.name}/>







