In any real-world application, data needs to be passed from one component to its children (parent-child communication).

To do this, we need to declare properties for the component, usually abbreviated to ‘props’.

The basic use

<! -- Parent app.svelte -->
<script>
  import Nested from './Nested.svelte';
</script>

<! -- 1. The components in svelte can be used directly after being introduced, and do not need to be imported and registered like vue. Component names are usually capitalized to distinguish between normal HTML tags and component elements.
<Nested answer={42} />


<! Nested.svelte -->
<script>
  // We use the export keyword to receive the corresponding props passed by the parent component
  export let answer;
</script>

<p>The answer is {answer}</p>
Copy the code

The default value

<! -- In child component -->
<script>
  // When we assign the props to be received, the value assigned is the default value of props
  export let answer = 'a mystery'; 
</script>

<! -- In parent component -->
<Nested answer={42} /> <! -- Subcomponent answer = 42 -->
<Nested/> <! -- the default value of the answer component is 'a mystery' -->
Copy the code

Launches the props

If your object has many attributes, you can ‘expand’ them into components without specifying them one by one

<script>
	import Info from './Info.svelte';

	const info = {
		name: 'Klaus'.age: 23.gender: 'male'.location: 'shanghai'
	}
</script>

<Info name={info.name} age={info.age} gender={info.gender} location={info.location}/>
<! Equivalent to the expansion operator in props and ES6
<Info {. info} / >
Copy the code

$$props

In the child component, there is a special variable $$props, which is of type object and defaults to an empty object

This object stores all props passed from the parent component to the child component (whether or not the prop is received with the export keyword in the child component)

<script>
	import Info from './Info.svelte';

	const pkg = {
		name: 'svelte'.version: 3.speed: 'blazing'.website: 'https://svelte.dev'
	};
</script>

<Info name={pkg.name} version={pkg.version} speed={pkg.speed} website={pkg.website}/>
<! {name: 'svelte', version: 3, speed: 'blazing', website: 'https://svelte.dev'} Tips: It is generally not recommended to use $$props directly, because Svelte is more difficult to optimize this operation, and it is useful in minimal cases. -->
Copy the code