当前位置:网站首页>Svelte 官方入门教程(3)—— Props
Svelte 官方入门教程(3)—— Props
2022-07-13 17:36:00 【Jason秀啊】
1、声明组件的 Props
到目前为止,我们只处理组件内部的状态,也就是说,这些值只能在给定的组件中访问。
在任何实际的应用程序中,您都需要将数据从一个组件传递到其子组件。为此,我们需要为组件声明 属性,通常缩写为 ‘props’。
参看下方的子组件 Nested.svelte 及父组件 App.svelte
Nested.svelte
<script> let answer; </script>
<p>The answer is {answer}</p>
App.svlete
<script> import Nested from './Nested.svelte'; </script>
<Nested answer={42}/>
在 Svelte 中,我们使用 export 关键字来实现接受父组件传递过来的属性值。
编辑 Nested.svelte 组件:
<script> export let answer; </script>
正如
$:一样,刚开始可能感觉有点怪异,export在 JavaScript 模块中正常的使用方式也不是这样的!暂且尝试先接受这种书写方式,很快它会成为你的第二天性。
别忘记我们在名称和值相同时,可以使用速记的方式书写,节省一些键盘的敲击量,例如src={src}的速记为 {src}。
2、属性默认值
在 Nested.svelte 中我们可以很方便就可以为 props 指定默认值:
<script> export let answer = 'a mystery'; </script>
如果我们现在编写第二个 Nested 组件且没有 answer 属性的话,它会用回默认值:
<Nested answer={42}/>
<Nested/>
3、展开 Props
如果你的对象拥有很多属性,你可以 ‘展开’ 它们到组件中,无需逐个指定:
<Info {...pkg}/>
相反,如果需要传递所有属性给组件,包括没有用
export声明的属性,可以直接使用$$props来赋值,不过一般不推荐直接使用它,因为 Svelte 较难优化这种操作,极小数情况下它很有用。
边栏推荐
猜你喜欢

c语言中的输入输出函数之scanf函数

ES6--模块化

Exploration and practice of integration of streaming and wholesale in jd.com

Kubernetes into the pit

Implementation of drop-down box function in SSM project

Research and development practice of Kwai real-time warehouse guarantee system

sql_ Server2014 download and installation

(CVPR-2022)用于改进步态识别的拉格朗日运动分析和视角嵌入
![[untitled]](/img/d8/a367c26b51d9dbaf53bf4fe2a13917.png)
[untitled]

ES6--类(class)
随机推荐
非功能方面测试
js--数据系统内置功能
c语言中的输入输出函数之printf函数
2022暑期实践(第一周)
41.js--闭包
数据库的基本相关概念整理
万建峰老师 干货分享2022年7月13日
Flink CDC MongoDB Connector 的实现原理和使用实践
Lombok @Data导致的hashCode的问题
Online multi line text batch regular replacement add suffix tool
JS作用域链
keil报错: ERROR 118 (ERRONEOUS REFERENCE TO EXTERNAL VARIABLES) 解决方案及原因
C语言:有关字符串函数的一些自我实现
数据类型与约束
ES6--面试题
Register the implementation.
命令行客户端的使用
38.js--原型练习案例(校招面试题)
快手实时数仓保障体系研发实践
New progress in the construction of meituan's Flink based real-time warehouse platform