Reputation: 1503
I'm currently working on a project with Vue.js and have a problem with using slots.
I have two components: PageView.vue
and SlotComponentView.vue
In SlotComponentView.vue
, there is a slot named Content that is used in PageView.vue
. For example, I add an input field to this slot, which is correctly inserted into the component at runtime.
Now, I want to read and save the content of this slot (specifically the value of the input field) from SlotComponentView.vue
at runtime. The goal is to implement something like a "savable filter". The filter has a slot where I can place any input (such as text fields), and in SlotComponentView.vue
, I want to use a button to read and save those inputs.
Does anyone have an idea how I can access the content of a slot at runtime in order to process the data in the parent component?
Thanks in advance.
Page.vue
<template>
<div>
<SlotComponent>
<template #content>
<input v-model="inputValue" type="text" />
</template>
</SlotComponent>
</div>
</template>
<script setup lang="ts">
const inputValue = ref("");
</script>
<style scoped></style>
SlotComponent.vue
<template>
<div>
<slot name="content" />
</div>
</template>
<script setup lang="ts">
function doSomethingWithTheSlotContentBasedOnWhatIsInside() {
// do something with the slot content
// i want to save the value of the input given in the slot content from outside
}
</script>
<style scoped></style>
Upvotes: 0
Views: 77
Reputation: 280
I think a good workaround for now until a better answer would be:
<template>
<div>
<SlotComponent :someNameYouWant="inputValue"> //<==== add this
<template #content>
<input v-model="inputValue" type="text" />
</template>
</SlotComponent>
</div>
</template>
<script setup lang="ts">
const inputValue = ref("");
</script>
then in the component:
<template>
<div>
<slot name="content" />
</div>
</template>
<script setup lang="ts">
const props = defineProps(['someNameYouWant'])
function doSomethingWithTheSlotContentBasedOnWhatIsInside() {
let lorem = props.someNameYouWant
//if this function must react to the value from props.someNameYouWant,
//just add a watcher for props.someNameYouWant that calls your function
}
</script>
<style scoped></style>
Upvotes: 0