Vue js从父组件到达子组件

bq3bfh9z  于 2023-08-07  发布在  Vue.js
关注(0)|答案(2)|浏览(144)

我有三个组件:FormCardButton
首先,我的Button.vue组件:

<template>
  <div>
    <slot v-bind="{ text }">
      <button>{{ text }}</button>
    </slot>
  </div>
</template>

<script setup>
const props = defineProps({
  text: {
    type: String,
    required: true
  }
});
</script>

字符串
下面是我的Card.vue组件:

<template>
  <Button text="{ text }">
    <template #default="{ text }">
      <button>{{ text }}</button>
    </template>
  </Button>
</template>

<script setup>
import Button from './Button.vue'

const props = defineProps({
  text: {
    type: String,
    required: true
  }
});
</script>


最后,这是我的Form.vue组件:

<template>
  <div>
    <Card text="Some text">
      <template #default="{ text }">
      </template>
    </Card>
  </div>
</template>

<script setup>
import Card from './Card.vue'
</script>


我的问题是,如何将文本从Form.vue传递到Button.vue子组件?

uujelgoq

uujelgoq1#

你的代码实际上是正确的。但是,如果你想在HTML属性中传递一个变量给组件,而不是使用text=,你应该使用:text=
而且Card.vueButton.vue属性都需要String,而不是传递{ }对象。因此,传递特定字符串而不是对象,如下所示::text="myVariableWithStringValue"

Card.vue

<template>
  <Button :text="buttonText"> <!-- here need use ":text" instead of "text" -->
    <template #default="{ text }">
      <button>{{ text }}</button>
    </template>
  </Button>
</template>

<script setup>
import Button from './Button.vue'

const props = defineProps({
  // I renamed your prop from 'props.text' to 'props.buttonText' so that we don't get confused by calling everything 'text'
  buttonText: {
    type: String,
    required: true
  }
});
</script>

字符串

Form.vue

<template>
  <div>
    <!-- I renamed your prop from 'props.text' to 'props.buttonText' so that we don't get confused by calling everything 'text' --> 
    <!-- If you want give text from variable then can use :buttonText="variableName" -->
    <!-- Now, just give to "Some text" string as buttonText -->
    <Card buttonText="Some text"></Card>
    <!-- And you can't use <template> in <Card> because don't have got defined <slot> in Card.vue's template -->
  </div>
</template>

<script setup>
import Card from './Card.vue'
</script>

fwzugrvs

fwzugrvs2#

Vue3 SFC Playground
看起来你过度使用了组件和插槽 prop ,你可以只使用命名插槽:
App.vue

<template>
  <div>
    <Card>
      <template #title>Card title</template>
      Some card content
      <template #button>Some button text</template>
    </Card>
  </div>
</template>

<script setup>
import Card from './Card.vue'

</script>

字符串
Card.vue:

<template>
    <h2><slot name="title"></slot></h2>
    <p>
    <slot></slot>
    </p>
    <Button>
        <slot name="button"></slot>
    </Button>
</template>

<script setup>
import Button from './Button.vue'
</script>


Button.vue:

<template>
    <div>
      <button><slot></slot></button>
    </div>
</template>

<script setup>
</script>

相关问题