How to get slot props with render functions in Vue? - vue.js

I'm trying to transform a Vue component I've made in a render function. Problem is I can't find a way to access the named slot props, like in the example:
<template #slot-name="slotProps">
<MyComponent v-bind="slotProps" />
</template>
There's a way to transform this code in a render function ?

To pass a scoped slot, use the scopedSlots property of the 2nd argument to h() (createElement()) in the form of { name: props => VNode | Array<VNode> }.
For example, assuming your template is:
<MySlotConsumer>
<template #mySlot="slotProps">
<MyComponent v-bind="slotProps" />
</template>
</MySlotConsumer>
The equivalent render function would be:
export default {
render(h) {
return h(MySlotConsumer, {
scopedSlots: {
mySlot: slotProps => h(MyComponent, { props: slotProps })
}
})
}
}
demo

Related

Vue render function: include slots to child component without wrapper

I'm trying to make a functional component that renders a component or another depending on a prop.
One of the output has to be a <v-select> component, and I want to pass it down all its slots / props, like if we called it directly.
<custom-component :loading="loading">
<template #loading>
<span>Loading...</span>
</template>
</custom-component>
<!-- Should renders like this (sometimes) -->
<v-select :loading="loading">
<template #loading>
<span>Loading...</span>
</template>
</v-select>
But I can't find a way to include the slots given to my functional component to the I'm rendering without adding a wrapper around them:
render (h: CreateElement, context: RenderContext) {
// Removed some logic here for clarity
return h(
'v-select',
{
props: context.props,
attrs: context.data.attrs,
on: context.listeners,
},
[
// I use the `slot` option to tell in which slot I want to render this.
// But it forces me to add a div wrapper...
h('div', { slot: 'loading' }, context.slots()['loading'])
],
)
}
I can't use the scopedSlots option since this slot (for example) has no slot props, so the function is never called.
return h(
'v-select',
{
props: context.props,
attrs: context.data.attrs,
on: context.listeners,
scopedSlots: {
loading(props) {
// Never called because no props it passed to that slot
return context.slots()['loading']
}
}
},
Is there any way to pass down the slots to the component i'm rendering without adding them a wrapper element?
I found out it's totally valid to use the createElement function to render a <template> tag, the same used to determine which slot we are on.
So using it like this fixes my problem:
render (h: CreateElement, context: RenderContext) {
// Removed some logic here for clarity
return h(
'v-select',
{
props: context.props,
attrs: context.data.attrs,
on: context.listeners,
},
[
// I use the `slot` option to tell in which slot I want to render this.
// <template> vue pseudo element that won't be actually rendered in the end.
h('template', { slot: 'loading' }, context.slots()['loading'])
],
)
}
In Vue 3 it's a way easier.
Check the docs Renderless Components (or playground)
An example from the docs:
App.vue
<script setup>
import MouseTracker from './MouseTracker.vue'
</script>
<template>
<MouseTracker v-slot="{ x, y }">
Mouse is at: {{ x }}, {{ y }}
</MouseTracker>
</template>
MouseTracker.vue
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
const x = ref(0)
const y = ref(0)
const update = e => {
x.value = e.pageX
y.value = e.pageY
}
onMounted(() => window.addEventListener('mousemove', update))
onUnmounted(() => window.removeEventListener('mousemove', update))
</script>
<template>
<slot :x="x" :y="y"/>
</template>
Just to mention, you can easily override CSS of the component in the slot as well.

Calling function inside child component without an event?

Currently trying to use a method belonging to the parent
<p class="message-date text-center">
{{ $emit('format_date_day_month_year_time', message.date) }}
</p>
However I am getting the error.
Converting circular structure to JSON
--> starting at object with constructor 'Object'
How can I call a function inside a child component that does not rely on an event? I apologize for asking such a simple question but everything I was able to find on google is using $emit and using an event.
$emit was designed to only trigger an event on the current instance of vue. Therefore, it is not possible to receive data from another component this way.
For your case, I would suggest to use Mixins especially if you need to use certain functions among multiple vue components.
Alternately, let the child component call the the parent through $emit then receive the result from the parent through a prop.
Your code could be something as follows:
Child component
<template>
<p class="message-date text-center">
{{ date }}
</p>
</template>
<script>
export default {
name: 'Child',
props: {
date: String,
},
mounted() {
this.$emit("format-date", message.date);
},
}
</script>
Parent component
<template>
<Child :date="childDate" #format-date="formatChildDate" />
</template>
<script>
import Child from '#/components/Child';
export default {
components: {
Child,
},
data: () => ({
childDate: '',
}),
methods: {
formatChildDate(date) {
this.childDate = this.formatDateDayMonthYearTime(date)
},
formatDateDayMonthYearTime(date) {
//return the formatted date
},
},
}
</script>
with $emit you call a function where the Parent can listento.
where you are using it i would suggest a computed prop of the function.
But back to your Question here is a example of emiting and listen.
//Parent
<template>
<MyComponent #childFunction="doSomethingInParent($event)"/>
</template>
//Child
<template>
<button #click="emitStuff">
</template>
.....
methods:{
emitStuff(){
this.$emit(childFunction, somedata)
}
with the event you can give Data informations to a Parentcomponent.

sending drop-down value to parent

I have this form on my parent:
<template>
<b-form #submit="onSubmit">
<CountryDropdown/>
</b-form>
</template>
<script>
import ...
export default {
form: {
country: ''
}
}
</script>
This is my Dropdown component using vue-select:
<template>
<v-select label="countryName" :options="countries" />
</template>
<script>
export default {
data() {
return {
countries: [
{ countryCode: 'EE', countryName: 'Estonia' },
{ countryCode: 'RU', countryName: 'Russia' }
]
}
}
}
</script>
I need to pass the countryCode value to its parent's form.country. I tried using $emit, but I cant seem to figure out how upon selection
it will set the parent value, and not upon submit.
EDIT:
The submitted solutions work great, I'll add my solution here:
I added an input event to my v-select:
<v-select #input="setSelected" ... />
in my script i define the selected and setSelected method :
data()
return
selected: ''
setSelected(value) {
this.selected = value.countryCode
this.$emit("selected", value.countryCode)
}
And in the parent:
<CountryDropdown v-on:selected="getCountry />
and parent script:
getCountry(country) {
this.form.country = country
}
You could use Vue's v-model mechanism to bind the output of vue-select to form.country in the container.
In CountryDropdown, implement v-model:
Add a prop named value 1️⃣, and bind it to vue-select.value 2️⃣
Emit input-event with the desired value. In this case, we want to emit countryCode as the value. 3️⃣
<template>
<v-select
:value="value" 2️⃣
#input="$emit('input', $event ? $event.countryCode : '')" 3️⃣
/>
</template>
<script>
export default {
props: ['value'], // 1️⃣
}
</script>
Now, the container of CountryDropdown could bind form.country to it, updating form.country to the selected country's countryCode upon selection:
<CountryDropdown v-model="form.country" />
demo
As you seem to know, $emit is what you need to use to send an event from a component to its' parent. To make that happen you need to add a few more things to your current code.
To get the options to list in your v-select you should use a computed function to isolate the names, like this:
computed: {
countryNames() {
return this.countries.map(c => c.countryName)
}
},
You will then need to list the names in your v-select like this:
<v-select label="countryName" :items="countryNames" #change="selectedCountry" />
You will see that #change is calling a method, this will be the method to emit your country code and it can do so like this:
methods: {
selectedCountry(e) {
let code = this.countries.find(cntry => cntry.countryName === e)
this.$emit('code', code.countryCode)
}
},
You will need a listener in your parent to hear the emit, so add something like this:
<CountryDropdown v-on:code="countryCodeFunction"/>
And then you just need a countryCodeFunction() in your methods that does something with the emitted code.

Vue how to get value from sub component

Here is my use case:
My main page have several sub-components that collect different input from user, finally I want to submit the whole page with all inputs collected. Therefore I want to retrieve the data from sub-component
One option is to use store, but my sub-components are super simple, just some forms, store seems too heavy...
Another option is that I can modify prop, although I know this is bad practice, but this approach looks just perfect....
Is it ok to modify prop if my logic is simple?(just collect inputs from user)Or I have to go for Vuex and store
Expanding on excellent answers from Ifaruki and Andres Foronda, another, related option is the use of the sync modifier on the child component's prop.
Suppose the child component has a prop named name. In the parent component, you can use the sync modifier like this:
<Child :name.sync="childName"></Child>
Then, in the child component, when the value of the name prop should be updated, don't update it directly. Instead, emit an event that follows the naming convention for sync-able props, which is update:nameOfProp. So in our example, the child component would do this:
this.$emit('update:name', newName);
The benefit of the sync modifier is that we don't have to write an event handler function in the parent component--Vue does that for us and updates the variable that is bound to the prop automatically.
You can read more details about the sync modifier in the official docs.
Retreiving data from sub component works with $emit here an exapmle:
//parent copmonent
<template>
<div>
<child #someEvent="someMethod"></child>
</div>
</template>
import child from "path/"
<script>
export default {
components: {
child
},
methods: {
someMethod(data){
console.log(data);
}
}
}
</script>
Child component
<template>
<div>
<button #click="sendEvent">send</button>
</div>
</template>
<script>
export default {
methods: {
sendEvent(){
this.$emit("someEvent", "working");
}
}
}
</script>
$emit takes 2 arguments. The first is the event name and the second one is the data that you send.
The parent just needs to listen with # for that event that being fired.
you can listen an event from child an update the parent data property
//parent component
<div>
<input-name #updateName="eventToUpdateName" /> <!--child component-->
</div>
...
data: () => ({ nameFromChild: '' )},
methods: {
eventToUpdateName(value) {
this.nameFromChild = value; // Update from child value emitted
}
}
...
And in the child component
// Child component
<input v-model="name" />
...
data: () => ({ name: '' }),
// watch for changes in the name property and emit an event, and pass the value to the parent
watch: { name() { this.$emit('updateName', this.name } }
...
Also, You can use a v-model directive and emit 'input' event from child.
//parent component
<div>
<input-name v-model="nameFromChild" /> <!--child component-->
</div>
...
data: () => ({ nameFromChild: '' )}
...
Now in the child component you can have
// Child component
<div>
<input v-model="name" />
</div>
data: () => ({ name: '' }),
props: { value: { type: String, default: '' },
created() { this.name = this.value }, // You can receive a default value
watch: { name() { this.$emit('input', this.name } }
...

Vue.js Generic Dynamic Component Rendering

I have a component that dynamic render components that get as props
<template>
<div>
<component :is="component" :data="data" v-if="component" />
</div>
</template>
<script>
export default {
name: 'dynamic-component-renderer',
props: ['data', 'type'],
computed: {
component() {
if (!this.type) {
return null;
}
return this.type;
},
}
}
</script>
The issue is in imports, I need to dynamic import, I know that I can do dynamic importing with webpack like this: () => import('./my-async-component'), but in my case, I don't need lazyLoad.
So I need to have a generic dummy component (dynamic-component-renderer) that will not know what components will get and dynamically render.