首页 > 解决方案 > 如何读取苗条组件的属性值

问题描述

组件.svelte

<script>
  export let hiddenStatus;
</script>

<div class:hidden={hiddenStatus}></div>

App.svelte

<script>
  import Component from "./Component.svelte";
</script>

<Component hiddenStatus={true}/>
{Component.hiddenStatus}

当我尝试获取它的属性值时,hiddenStatus它显示为undefined. 我该如何解决这个问题?

标签: svelte

解决方案


您可以使用bind:this组件指令以编程方式与组件实例进行交互。

accessors请注意,除非您使用settrue或进行编译,否则无法直接从组件实例中读取 props <svelte:options accessors/>

例子

<!-- Component.svelte -->
<script>
  export let hiddenStatus;
</script>

<div class:hidden={hiddenStatus}></div>

<!-- App.svelte -->
<script>
  import { onMount } from "svelte";
  import Component from "./Component.svelte";

  let component;
    
  onMount(() => {
    console.log(component.hiddenStatus);
  });
</script>

<Component hiddenStatus={true} bind:this={component}/>

推荐阅读