Access this.$slots while using v-slot (scoped-slot) - javascript

In a specific use-case, I have to access the DOM element inside a slot to get its rendered width and height. With normal slots, this works by accessing this.$slots.default[0].elm.
Now I added a scoped-slot to access data inside the component, which led to this.$slots being empty and breaking my code.
How is it possible to access the DOM element of a slot that is using a slot-scope?
Basic example code (notice while using a scoped-slot, this.$slots results in {}; while using a normal slot, it results in {default: Array(1)}):
App.vue:
<template>
<div id="app">
<HelloWorld v-slot="{ someBool }">
<p>{{ someBool }}</p>
<h1>Hello</h1>
</HelloWorld>
<HelloWorld>
<h1>Hello</h1>
</HelloWorld>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue';
export default {
name: 'App',
components: {
HelloWorld,
},
};
</script>
HelloWorld.vue:
<template>
<div class="hello">
<slot :someBool="someBool" />
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data() {
return {
someBool: false,
};
},
mounted() {
console.log(this.$slots);
},
};
</script>

Use $scopedSlots, which includes both scoped slots and non-scoped slots:
export default {
mounted() {
console.log(this.$scopedSlots.default())
}
}
demo

Maybe not directly related but wanted to share how to access slot values.
resources/js/components/product/Filter.vue
<template>
<span class="ml-5">
The Slot Values: <span class="text-yellow-400">{{filterValues}}</span>
</span>
</template>
<script>
export default {
data() {
return {
filterValues: ''
}
},
mounted() {
this.filterValues = this.$slots.default()[0].children
}
}
</script>
resources/views/products.blade.php
...
<product-filter-vue>Instrument, FX</product-filter-vue>
...

Related

Update props in component through router-view in vue js

I want to pass a boolean value from one of my views in a router-view up to the root App.vue and then on to one of the components in the App.vue. I was able to do it but I am facing an error:
Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "drawer"
Below is my code:
Home.vue:
<template>
<div class="home" v-on:click="updateDrawer">
<img src="...">
</div>
</template>
<script>
export default {
name: "Home",
methods:{
updateDrawer:function(){
this.$emit('updateDrawer', true)
}
};
</script>
The above view is in the router-view and I am getting the value in the App.vue below:
<template>
<v-app class="">
<Navbar v-bind:drawer="drawer" />
<v-main class=" main-bg">
<main class="">
<router-view v-on:updateDrawer="changeDrawer($event)"></router-view>
</main>
</v-main>
</v-app>
</template>
<script>
import Navbar from '#/components/Navbar'
export default {
name: 'App',
components: {Navbar},
data() {
return {
drawer: false
}
},
methods:{
changeDrawer:function(drawz){
this.drawer = drawz;
}
},
};
</script>
I am sending the value of drawer by binding it in the navbar component.
Navbar.vue:
<template>
<nav>
<v-app-bar app fixed class="white">
<v-app-bar-nav-icon
class="black--text"
#click="drawer = !drawer"
></v-app-bar-nav-icon>
</v-app-bar>
<v-navigation-drawer
temporary
v-model="drawer"
>
...
</v-navigation-drawer>
</nav>
</template>
<script>
export default {
props:{
drawer:{
type: Boolean
}
},
};
</script>
This will work one time and then it will give me the above error. I appreciate if any one can explain what should I do and how to resolve this issue.
In Navbar.vue you are taking the property "drawer" and whenever someone clicks on "v-app-bar-nav-icon" you change drawer to be !drawer.
The problem here is that you are mutating (changing the value) of a property from the child side (Navbar.vue is the child).
That's not how Vue works, props are only used to pass data down from parent to child (App.vue is parent and Navbar.vue is child) and never the other way around.
The right approach here would be: every time, in Navbar.vue, that you want to change the value of "drawer" you should emit an event just like you do in Home.vue.
Then you can listen for that event in App.vue and change the drawer variable accordingly.
Example:
Navbar.vue
<v-app-bar-nav-icon
class="black--text"
#click="$emit('changedrawer', !drawer)"
></v-app-bar-nav-icon>
App.vue
<Navbar v-bind:drawer="drawer" #changedrawer="changeDrawer"/>
I originally missed the fact that you also used v-model="drawer" in Navbar.vue.
v-model also changes the value of drawer, which again is something we don't want.
We can solve this by splitting up the v-model into v-on:input and :value like so:
<v-navigation-drawer
temporary
:value="drawer"
#input="val => $emit('changedrawer', val)"
>
Some sort of central state management such as Vuex would also be great in this scenario ;)
What you could do, is to watch for changes on the drawer prop in Navbar.vue, like so:
<template>
<nav>
<v-app-bar app fixed class="white">
<v-app-bar-nav-icon
class="black--text"
#click="switchDrawer"
/>
</v-app-bar>
<v-navigation-drawer
temporary
v-model="navbarDrawer"
>
...
</v-navigation-drawer>
</nav>
</template>
<script>
export default {
data () {
return {
navbarDrawer: false
}
},
props: {
drawer: {
type: Boolean
}
},
watch: {
drawer (val) {
this.navbarDrawer = val
}
},
methods: {
switchDrawer () {
this.navbarDrawer = !this.navbarDrawer
}
}
}
</script>
Home.vue
<template>
<div class="home">
<v-btn #click="updateDrawer">Updrate drawer</v-btn>
</div>
</template>
<script>
export default {
name: 'Home',
data () {
return {
homeDrawer: false
}
},
methods: {
updateDrawer: function () {
this.homeDrawer = !this.homeDrawer
this.$emit('updateDrawer', this.homeDrawer)
}
}
}
</script>
App.vue
<template>
<v-app class="">
<Navbar :drawer="drawer" />
<v-main class="main-bg">
<main class="">
<router-view #updateDrawer="changeDrawer"></router-view>
</main>
</v-main>
</v-app>
</template>
<script>
import Navbar from '#/components/Navbar'
export default {
name: 'App',
components: { Navbar },
data () {
return {
drawer: false
}
},
methods: {
changeDrawer (newDrawer) {
this.drawer = newDrawer
}
}
}
</script>
This doesn't mutate the drawer prop, but does respond to changes.

Provide a ref to inject it in a child component with Vue js

Anybody knows how to provide a ref to child components. For example:
Parent component provide the ref:
<template>
<div ref="myRef" />
</template>
<script>
export default {
name: 'SearchContainer',
provide: {
parentRef: this.$refs.myRef
}
}
</script>
</style>
And Child component inject it:
<template>
<div />
</template>
<script>
export default {
name: 'SearchCard',
inject: ['parentRef']
}
</script>
</style>
Generally the interaction between parent and child component should be done using props and emitted events :
<template>
<div />
</template>
<script>
export default {
methods:{
changeParentStyle(){
this.$emit('change-style')
}
}
}
</script>
</style>
parent :
<template>
<child #change-style="changeStyle" />
</template>
<script>
export default {
name: 'SearchContainer',
methods:{
changeStyle(){
//change the property that affects your style
}
}
}
</script>
</style>
I have manage to achieve providing ref to children. But in my opinion if you want to communicate betwwen parent and children I think you have got your answer already by Boussadjra Brahim.
Still providing ref has its own use cases. I am usinig it for dialogs.
Here is my solution:
<!-- Parent Component -->
<template>
<div ref="myRef"></div>
</template>
<script>
export default {
name: 'SearchContainer',
methods:{
getMyRef(){
return this.$refs.myRef
}
},
provide() {
return{
parentRef: this.getMyRef
}
}
}
</script>
<!-- Child Component -->
<template>
<div></div>
</template>
<script>
export default {
name: 'SearchContainer',
methods:{
useRef(){
this.parentRef().data // Can access data properties
this.parentRef().method() // can access methods
}
}
inject: ['parentRef']
}
</script>

How to Access Component HTML output in Vue outside the template tag?

I know that we can simply show the component output with <ComponentName/> inside the template,
but how do we access ComponentName html output outside the template like in data, methods, or during mounted
e.g. components/Test.vue
<template>
<div>I'm a test</div>
</template>
in another vue file pages/ViewTest.vue
import Test from '~/components/Test.vue'
export default {
components: {Test},
data() {
return {
test: Test
}
},
mounted: function() {
console.log( Test ) // Output is Test Component Object
console.log( this.test ) // Output is Test Component Object
}
}
The object from console log output seems to contain a lot of information and I can even see a render property from the object although when I try console.log( Test.render() ) its giving me error
So My question is how can I get the <div>I'm a test</div> from outside the template?
Appreciate any help or guidance
EDIT
I'm using vue-material-design-icons package for generating different svg icons,
and I can use it like below
<template>
<MapMarkerRadius/>
</template>
<script>
import MapMarkerRadius from 'vue-material-design-icons/MapMarkerRadius'
export default {
components: {MapMarkerRadius}
}
</script>
Now here's my main issue,
I have this component that generates an html
<template>
<div :class="'card'">
<div v-if="title" :class="'card-title'">
{{ title }}
</div>
<div :class="'card-content'">
<slot />
</div>
</div>
</template>
<script>
export default {
name: 'card',
props: {
title: {},
}
};
</script>
Then I'm using that card component like this on a different vue file
<template>
<card :title="'Title ' + MapMarkerRadius">
Test Content
</card>
</template>
<script>
import card from '~/components/Card'
import MapMarkerRadius from 'vue-material-design-icons/MapMarkerRadius'
export default {
components: {card, MapMarkerRadius}
};
</script>
and my problem here is that the output of the card title is Title [object]
Try to use ref in the root of the Test component like :
<template>
<div ref="test">I'm a test</div>
</template>
in other component do :
mounted: function() {
console.log( this.$refs.test )
}
No need to import the component.
The repo that you are using are single-file components that generates html through a single tag, so using
import MapMarkerRadius from 'vue-material-design-icons/MapMarkerRadius'
will enable you to use it in template as <map-marker-radius/>
That is why appending the string title and an object like "My Icon"+MapMarkerRadius will return the literal [object] as you've seen: "My Icon [object]"
You have 3 options to go through what you want:
Search for other repos that enable you to use easily material icons in other means;
You have access to the card component? You can use the class names of this repo instead rather than the svg version or the component itself: https://github.com/robcresswell/vue-material-design-icons/issues/12, add the class names to the props and add it to your component:
<card :title="'Title'" :icon_class="map-marker-radius">
Test Content
</card>
<div v-if="title" :class="'card-title'">
{{ title }} <div :class="icon_class"></div>
</div>
props: {
title: {},
icon_class: '',
}
You can use the MapMarkerRadius component directly in card component but only appears when you pass a certain criteria on the card component, such like:
main.vue
<template>
<card :title="'Title'" :icon="true" :icon_typename="'map-marker-radius'">
Test Content
</card>
</template>
<script>
import card from '~/components/Card'
export default {
components: {card}
};
</script>
with icon_typename as any name/keyword you'd like to use.
card.vue
<template>
<div :class="'card'">
<div v-if="title" :class="'card-title'">
{{ title }} <span v-if="icon_mmr"><map-marker-radius/></span>
</div>
<div :class="'card-content'">
<slot />
</div>
</div>
</template>
<script>
import MapMarkerRadius from 'vue-material-design-icons/MapMarkerRadius'
export default {
name: 'card',
props: {
title: {},
icon: { default: false },
icon_typename: '',
icon_mmr: false,
},
mounted(){
if (this.icon && this.icon_typename === 'map-marker-radius') this.icon_mmr = true
},
components: { MapMarkerRadius },
};
</script>
The code is far from perfect but you can go from there to optimize further.

Vue.js render multiple slots

I have the following app:
<template>
<component :is="layout">
<router-view :layout.sync="layout"/>
</component>
</template>
<script>
import LayoutBlank from './LayoutBlank'
export default {
name: 'app',
data() {
return {
layout: LayoutBlank,
};
},
}
</script>
<script>
import LayoutBlankTemplate from './LayoutBlankTemplate'
export default {
name: 'LayoutBlank',
created() {
this.$parent.$emit('update:layout', LayoutBlankTemplate);
},
render() {
return this.$slots.default[0];
},
}
</script>
<template>
<div>
<slot></slot>
</div>
</template>
<script>
export default {
name: 'LayoutBlankTemplate',
}
</script>
<template>
<layout-blank>
Test content
</layout-blank>
</template>
<script>
import LayoutBlank from './LayoutBlank';
export default {
name: 'BlankTest',
components: {LayoutBlank},
}
</script>
All works fine. But now I would like to add one more slot to the LayoutBlankTemplate:
<template>
<div>
<slot></slot>
<slot name="second"></slot>
</div>
</template>
<script>
export default {
name: 'LayoutBlankTemplate',
}
</script>
and use it in BlankTest:
<template>
<layout-blank>
<template #default>Test content</template>
<template #second>Second test content</template>
</layout-blank>
</template>
<script>
import LayoutBlank from './LayoutBlank';
export default {
name: 'BlankTest',
components: {LayoutBlank},
}
</script>
The code renders only the default slot content. The problem is that I'm using the return this.$slots.default[0]; in LayoutBlank component which renders only the default slot content.
I cannot find the way how to render all slots in LayoutBlank::render() method. I know that I'm able to get the slots list using this.$slots or this.$scopedSlots but I can't find the way how to pass them to the LayoutBlankTemplate to make them render.
You could put the slots into elements you create I believe. This is mentioned (briefly) in the render function documentation.
This may not be exactly the layout you want, but for example,
<script>
import LayoutBlankTemplate from './LayoutBlankTemplate'
export default {
name: 'LayoutBlank',
created() {
this.$parent.$emit('update:layout', LayoutBlankTemplate);
},
render(createElement, context) {
return createElement('div', {}, [
createElement('div', {}, this.$slots.default),
createElement('div', {}, this.$slots.second)
])
},
}
</script>

VueJS pass all props to child component

I am quite new to VueJS. In react you can easily use rest params for passing props to children. Is there a similar pattern in Vue?
Consider this parent component that has a few children components:
<template>
<header class="primary-nav">
<search-bar :config="searchBar"><search-bar>
// ^^^^ this becomes the key on the props for SearchBar
header>
</template>
export default {
data(){
return {
... a few components ...
searchBar : {
model: '',
name: 'search-bar',
placeholder: 'Search Away',
required:true,
another: true
andanother: true,
andonemoreanotherone:true,
thiscouldbehundredsofprops:true
}
}
}
}
<template>
<div :class="name">
<form action="/s" method="post">
<input type="checkbox">
<label :for="config.name" class="icon-search">{{config.label}}</label>
<text-input :config="computedTextInputProps"></text-input>
//^^^^ and so on. I don't like this config-dot property structure.
</form>
</div>
</template>
export default {
props: {
name: String,
required: Boolean,
placeholder: String,
model: String,
},
computed: {
computedtextInputProps(){
return justThePropsNeededForTheTextInput
}
}
...
What I don't like is that the props are named-spaced with the key config, or any other arbitrary key. The text-input component ( not shown ) is a glorified input field that can take a number of attributes. I could flatten the props when the component is created, but is that generally a good idea?
I am surprised this question hasn't been asked before.
Thanks.
Edit: 10-06-2017
Related: https://github.com/vuejs/vue/issues/4962
Parent component
<template>
<div id="app">
<child-component v-bind="propsToPass"></child-component>
</div>
</template>
<script>
import ChildComponent from './components/child-component/child-component'
export default {
name: 'app',
components: {
ChildComponent
},
data () {
return {
propsToPass: {
name: 'John',
last_name: 'Doe',
age: '29',
}
}
}
}
</script>
Child Component
<template>
<div>
<p>I am {{name}} {{last_name}} and i am {{age}} old</p>
<another-child v-bind="$props"></another-child> <!-- another child here and we pass all props -->
</div>
</template>
<script>
import AnotherChild from "../another-child/another-child";
export default {
components: {AnotherChild},
props: ['name', 'last_name', 'age'],
}
</script>
Another Child component inside the above component
<template>
<h1>I am saying it again: I am {{name}} {{last_name}} and i am {{age}} old</h1>
</template>
<script>
export default {
props: ['name', 'last_name', 'age']
}
</script>
Parent component
You can pass as many props as you want to child component
Child Component
Once you are satisfied with all the props, then you can use v-bind="$props" inside your child component to retrieve all the props.
Final Result:
Done:)
In Vue 2.6+, in addition to attributes passing,
events/listeners can be also passed to child components.
Parent component
<template>
<div>
<Button #click="onClick">Click here</Button>
</div>
</template>
<script>
import Button from "./Button.vue";
export default {
methods:{
onClick(evt) {
// handle click event here
}
}
}
</script>
Child component
Button.vue
<template>
<button v-bind="$attrs" v-on="$listeners">
<slot />
</button>
</template>
Update [2021-08-14]:
In Vue 3, $listeners will be removed. $attrs will have both listeners and attributes passing to the child component.
Child component
Button.vue
<template>
<button v-bind="$attrs">
<slot />
</button>
</template>
Migration Guide
In the child component, you can bind $attrs and $props.
<template>
<button v-bind="[$props,$attrs]" v-on="$listeners">
<slot />
</button>
</template>
v-bind="[$attrs, $props]"
This one works for me. $attrs doesn't include props.

Categories

Resources