svelte教程(3)props

在任何實(shí)際應(yīng)用程序中,您都需要將數(shù)據(jù)從一個(gè)組件傳遞到其子組件。為此,我們需要聲明properties,通常將其縮寫(xiě)為'props'。
注意:Svelte中,我們使用export關(guān)鍵字來(lái)實(shí)現(xiàn)。export的工作原理與JavaScript中不同。

// Nested.svelte
<script>
    export let answer;
</script>
<p>The answer is {answer}</p>


// index.svelte
<script>
    import Nested from '../components/Nested';
</script>
<Nested answer={42}/>

指定props默認(rèn)值,例如:

// Nested.svelte
<script>
    export let answer='a mystery';
</script>
<p>The answer is {answer}</p>


// index.svelte
<script>
    import Nested from '../components/Nested';
</script>
<Nested answer={42}/>
<Nested/>

如果您有一個(gè)屬性對(duì)象,則可以將它們“擴(kuò)展”到一個(gè)組件上,而不用指定每個(gè)對(duì)象:

// Info.svelte
<script>
    export let name;
    export let github;
    export let version;
</script>
<div>
    <p>The name is {name}</p>
    <a href={github}>The github is {github}</a>
    <p>The version is {version}</p>
</div>

// index.svelte
<script>
  import Info from "../components/Info";
  let info = {
    name: "sullay",
    github: "https://github.com/sullay/svelte-learn",
    version: "1.0.0"
  };
</script>
<Info {...info} />

本教程的所有代碼均上傳到github有需要的同學(xué)可以參考 https://github.com/sullay/svelte-learn。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容