美文网首页
Getting started with Svelte - Pr

Getting started with Svelte - Pr

作者: 游文影月志 | 来源:发表于2023-11-24 17:16 被阅读0次

    Declaring props

    So far, we've dealt exclusively with internal state — that is to say, the values are only accessible within a given component.

    In any real application, you'll need to pass data from one component down to its children. To do that, we need to declare properties, generally shortened to 'props'. In Svelte, we do that with the export keyword.

    App.svelte

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

    Nested.svelte

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

    Default values

    We can easily specify default values for props in Nested.svelte:
    Nested.svelte

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

    If we now add a second component without an answer prop, it will fall back to the default:
    App.svelte

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

    Spread props

    If you have an object of properties, you can ‘spread’ them onto a component instead of specifying each one:

    PackageInfo.svelte

    <script>
        export let name;
        export let version;
        export let speed;
        export let website;
    
        $: href = `https://www.npmjs.com/package/${name}`;
    </script>
    
    <p>
        The <code>{name}</code> package is {speed} fast. Download version {version} from
        <a {href}>npm</a> and <a href={website}>learn more here</a>
    </p>
    

    App.svelte

    <script>
        import PackageInfo from './PackageInfo.svelte';
    
        const pkg = {
            name: 'svelte',
            speed: 'blazing',
            version: 4,
            website: 'https://svelte.dev'
        };
    </script>
    
    <PackageInfo {...pkg} />
    

    相关文章

      网友评论

          本文标题:Getting started with Svelte - Pr

          本文链接:https://www.haomeiwen.com/subject/eolgwdtx.html