Vue – pass variable from child template to App.vue - vue.js

I read up on passing variables from child to parent using $emit but I can't fully figure it out yet.
In App.vue I have a <header/> component for the page header containing a button which controls the mobile navigation's visibility. On click it changes its class:
<button #click="toggleMobileNavigation" :class="isOpen ? 'is-open' : 'is-closed'">
The <header/>'s js:
export default {
data() {
return {
isOpen: false,
};
},
methods: {
toggleMobileNavigation() {
if(!this.isOpen) {
this.isOpen = true;
} else {
this.isOpen = false;
}
this.$emit(this.isOpen)
}
}
}
The App.vue:
<Header />
<main id="main" tabindex="-1" class="main" :class="isOpen">
This obviously this doesn't work and I can't figure out what the right way is to catch the $emit.
Thanks for any tips!

I would say you are on the right track, this child needs to emit some event to alert its parent of an important change.
But instead of doing this in your Header component:
this.$emit(this.isOpen)
Supply an event name:
this.$emit('opened', this.isOpen)
// or:
if (this.isOpen) {
this.$emit('opened');
} else {
this.$emit('closed');
}
The way you catch this event in the parent component (App.vue) should be:
<Header #opened="handleOpenedEvent"> // will call method handleOpenedEvent
// alternatively:
<Header #opened="menuStatus = $event"> // $event contains data you supply as second argument to your this.$emit(name, ...) call
// #[eventname] is one way of doing it, v-on is the same:
<Header v-on:opened="handleEvent">

Related

How to add class to the parent component when the button is clicked in child in vue

I have a button in my child component and when I click this button I want to add a class in my parent component. I added child component as a slot in parent component.
parent component:
<template>
<div :class="editMode ? 'class-add' : ''">
<slot name="default"></slot>
</div>
</template>
<script>
export default {
props: {
editMode: {
type: Boolean,
required: true,
},
},
};
</script>
child component:
<button #click="addClass">Click Me!!!</button>
addClass() {
this.$emit('edit-abc', true);
},
And here how I am adding the class:
<parent-component :edit-mode="editMode">
<template #default>
<child-component #edit-abc="editAbc($event)" />
</template>
</parent-component>
The problem is as you see, I have several abcs (abcs is an object which includes several abc) to send to child the class only the one which is clicked. So I believe here #edit-abc="editMode = $event", instead of editMode = $event, I need to create a function and filter the one that I want to add the class but my logic is wrong somewhere. Here what I have done as a function.
editAbc(event) {
this.abcs.filter((a) => {
if (a.id) {
this.$nextTick(() => {
return (this.editMode = event);
});
}
});
},
You have to declare the editMode data property to use it in your event handling.
data() {
return {
editMode: false
};
}
If you need to send separate events, then simply use different events.
You intentions with "several abcs" are not really clear. And it looks for me like you have a design flaw.
Please clarify it further.
UPDATE
Here is a stackblitz with the solution.

Vue 3: How to change specific sibling component's data?

Say you have 3 components:
<Modal>
<Navbar>
<Hero>
Your Modal component has data saying whether it's open or not, along with the appropriate methods:
data() {
return {
active: false,
}
},
methods: {
open() {this.active = true},
close() {this.active = false},
switch() {this.active ? this.close(): this.open()}
}
and you want a link in your Navbar component to be able to open it:
template:
/*html*/
`<nav class="navbar">
<router-link :to="etc.">Home</router-link>
<router-link :to="etc.">About</router-link>
<a #click="openSiblingModalSomehow">Contact</a> <!-- This one -->
</nav>`
As well as the Call to Action button on your Hero component:
template:
/*html*/
`<div class="hero">
<h1>Hello, World</h1>
<button #click="openSiblingModelSomehow">Contact Me</button>
</div>`
Assuming you DON'T want a global property to access this... For example, what if you want more than one type of modal?:
<ContactModal>
<SignUpModal>
<OtherModal>
<Navbar>
<Hero>
and knowing that the Modal also needs to be able to close itself,
How would you trigger a specific sibling element / component to open the Modal (in this case, let's say ContactModal) using Vue 3?
I thought about using a variable on the App itself, but it seems a bit hectic to change a globalProperty only for a specific component with it's own data.
I had a similar challenge at my project. My approach was to not use a Boolean property.
Step by step, first declare a empty string at the parent, that provides it for your modal boxes:
data() {
return {
active: ""
}
}
Declare a method, that handles that string:
methods: {
switchActive(string) {
if (string) {
this.active = string;
}
else {
this.active = ""
}
}
}
This would be one of your modal components:
<template>
<Dialog header="Header" footer="Footer" :visible="checkActive">
I am the modal dialog.
<button #click="this.$emit('close')">Close Me</button>
</Dialog>
</template>
<script>
export default {
name: "modal-123",
props: {
active: String
},
computed: {
checkActive() {
return this.active === this.$options.name;
}
}
}
</script>
And call this component:
<modal :active="active" #close="switchActive('')"></modal>
If you want to open one of your modal boxes, you call switchActive with the name property of your modal box.

Vue.js Dynamically extend/replace child component method at runtime with access to parent scope

Is it possible to extend child component function at runtime in vue? I want to limit/stop child component function call based on parent scope logic (I want to avoid passing props in this specific case).
Overriding a component method is not a runtime solution/I can't have access to parent scope.
What I have tried and it does not working:
// Foo.vue
<template>
<button #click="func">Click me</button>
</template>
export default {
methods: {
func() {
console.log('some xhr')
}
}
}
// Bar.vue
<template>
<Foo ref="foo"/>
</template>
export default {
components: {Foo}
mounted() {
this.$nextTick(() => {
this.$refs.foo.func = function() {
console.log('some conditional logic')
this.$refs.foo.func()
}
})
}
}
For this usecase a better implementation would be defining the function in the parent itself and passing it through props. Since props are by default reactive you can easily control it from parent.
// Foo.vue
<template>
<button #click="clickFunction.handler">Click me</button>
</template>
export default {
name: 'Foo',
props: {
clickFunction: {
type: Object,
required: true
}
}
}
// Bar.vue
<template>
<Foo :clickFunction="propObject"/>
</template>
export default {
components: {Foo},
data() {
return {
propObject: {
handler: null;
}
};
}
mounted() {
this.$nextTick(() => {
if(some condition) {
this.propObject.handler = this.func();
} else this.propObject.handler = null;
})
},
methods: {
func() {
console.log('some xhr')
}
}
}
From what I managed to realize:
the solution in the code posted in the question really replaces the func() method in the child component. It's just that Vue has already attached the old method to the html element. Replacing it at the source will have no impact.
I was looking for a way to re-attach the eventListeners to html component. Re-rendering using an index key would not help because it will re-render the component with its original definition. You can hide the item in question for a split second, and when it appears you will receive an updated eventListener. However, this involves an intervention in the logic of the child component (which I avoid).
The solution is the $forceUpdate() method.
Thus, my code becomes the following:
// Foo.vue
<template>
<button #click="func">Click me</button>
</template>
export default {
methods: {
func() {
console.log('some xhr')
}
}
}
// Bar.vue
<template>
<Foo ref="foo"/>
</template>
export default {
components: {Foo}
mounted() {
this.$nextTick(() => {
let original = this.$refs.foo.func; // preserve original function
this.$refs.foo.func = function() {
console.log('some conditional logic')
original()
}
this.$refs.btn.$forceUpdate(); // will re-evaluate visual logic of child component
})
}
}

Vue best practice for calling a method in a child component

I have been reading lots of articles about this, and it seems that there are multiple ways to do this with many authors advising against some implementations.
To make this simple I have created a really simple version of what I would like to achieve.
I have a parent Vue, parent.vue. It has a button:
<template>
<div>
<button v-on:click="XXXXX call method in child XXXX">Say Hello</button>
</div>
</template>
In the child Vue, child.vue I have a method with a function:
methods: {
sayHello() {
alert('hello');
}
}
I would like to call the sayHello() function when I click the button in the parent.
I am looking for the best practice way to do this. Suggestions I have seen include Event Bus, and Child Component Refs and props, etc.
What would be the simplest way to just execute the function in my method?
Apologies, this does seem extremely simple, but I have really tried to do some research.
Thanks!
One easy way is to do this:
<!-- parent.vue -->
<template>
<button #click="$refs.myChild.sayHello()">Click me</button>
<child-component ref="myChild" />
</template>
Simply create a ref for the child component, and you will be able to call the methods, and access all the data it has.
You can create a ref and access the methods, but this is not recommended. You shouldn't rely on the internal structure of a component. The reason for this is that you'll tightly couple your components and one of the main reasons to create components is to loosely couple them.
You should rely on the contract (interface in some frameworks/languages) to achieve this. The contract in Vue relies on the fact that parents communicate with children via props and children communicate with parents via events.
There are also at least 2 other methods to communicate when you want to communicate between components that aren't parent/child:
the event bus
vuex
I'll describe now how to use a prop:
Define it on your child component
props: ['testProp'],
methods: {
sayHello() {
alert('hello');
}
}
Define a trigger data on the parent component
data () {
return {
trigger: 0
}
}
Use the prop on the parent component
<template>
<div>
<childComponent :testProp="trigger"/>
</div>
</template>
Watch testProp in the child component and call sayHello
watch: {
testProp: function(newVal, oldVal) {
this.sayHello()
}
}
Update trigger from the parent component. Make sure that you always change the value of trigger, otherwise the watch won't fire. One way of doing this is to increment trigger, or toggle it from a truthy value to a falsy one (this.trigger = !this.trigger)
I don't like the look of using props as triggers, but using ref also seems as an anti-pattern and is generally not recommended.
Another approach might be: You can use events to expose an interface of methods to call on the child component this way you get the best of both worlds while keeping your code somehow clean. Just emit them at the mounting stage and use them when pleased. I stored it in the $options part in the below code, but you can do as pleased.
Child component
<template>
<div>
<p>I was called {{ count }} times.</p>
</div>
</template>
<script>
export default {
mounted() {
// Emits on mount
this.emitInterface();
},
data() {
return {
count: 0
}
},
methods: {
addCount() {
this.count++;
},
notCallable() {
this.count--;
},
/**
* Emitting an interface with callable methods from outside
*/
emitInterface() {
this.$emit("interface", {
addCount: () => this.addCount()
});
}
}
}
</script>
Parent component
<template>
<div>
<button v-on:click="addCount">Add count to child</button>
<child-component #interface="getChildInterface"></child-component>
</div>
</template>
<script>
export default {
// Add a default
childInterface: {
addCount: () => {}
},
methods: {
// Setting the interface when emitted from child
getChildInterface(childInterface) {
this.$options.childInterface = childInterface;
},
// Add count through the interface
addCount() {
this.$options.childInterface.addCount();
}
}
}
</script>
With vue 3 composition api you can do it like this:
Parent.vue
<script setup lang="ts">
const childRef = ref()
const callSayHello = () => {
childRef.value.sayHello()
}
</script>
<template>
<child ref="childRef"></child>
</template>
<style scoped></style>
Child.vue
<script setup lang="ts">
const sayHello = () => {
console.log('Hello')
}
defineExpose({ sayHello })
</script>
<template></template>
<style scoped></style>
I am not sure is this the best way. But I can explain what I can do...
Codesandbox Demo : https://codesandbox.io/s/q4xn40935w
From parent component, send a prop data lets say msg. Have a button at parent whenever click the button toggle msg true/false
<template>
<div class="parent">
Button from Parent :
<button #click="msg = !msg">Say Hello</button><br/>
<child :msg="msg"/>
</div>
</template>
<script>
import child from "#/components/child";
export default {
name: "parent",
components: { child },
data: () => ({
msg: false
})
};
</script>
In child component watch prop data msg. Whenever msg changes trigger a method.
<template>
<div class="child">I am Child Component</div>
</template>
<script>
export default {
name: "child",
props: ["msg"],
watch: {
msg() {
this.sayHello();
}
},
methods: {
sayHello() {
alert("hello");
}
}
};
</script>
This is an alternate take on Jonas M's excellent answer. Return the interface with a promise, no need for events. You will need a Deferred class.
IMO Vue is deficient in making calling child methods difficult. Refs aren't always a good option - in my case I need to call a method in one of a thousand grandchildren.
Parent
<child :getInterface="getInterface" />
...
export default {
setup(props) {
init();
}
async function init() {
...
state.getInterface = new Deferred();
state.childInterface = await state.getInterface.promise;
state.childInterface.doThing();
}
}
Child
export default {
props: {
getInterface: Deferred,
},
setup(props) {
watch(() => props.getInterface, () => {
if(!props.getInterface) return;
props.getInterface.resolve({
doThing: () => {},
doThing2: () => {},
});
});
}
}

Vue component wrapping

What is the correct way to wrap a component with another component while maintaining all the functionality of the child component.
my need is to wrap my component with a container, keeping all the functionality of the child and adding a trigger when clicking on the container outside the child that would trigger the child`s onclick event,
The parent component should emit all the child component events and accept all the props the child component accepts and pass them along, all the parent does is add a clickable wrapper.
in a way im asking how to extend a component in vue...
It is called a transparent wrapper.
That's how it is usually done:
<template>
<div class="custom-textarea">
<!-- Wrapped component: -->
<textarea
:value="value"
v-on="listeners"
:rows="rows"
v-bind="attrs"
>
</textarea>
</div>
</template>
<script>
export default {
props: ['value'], # any props you want
inheritAttrs: false,
computed: {
listeners() {
# input event has a special treatment in this example:
const { input, ...listeners } = this.$listeners;
return listeners;
},
rows() {
return this.$attrs.rows || 3;
},
attrs() {
# :rows property has a special treatment in this example:
const { rows, ...attrs } = this.$attrs;
return attrs;
},
},
methods: {
input(event) {
# You can handle any events here, not just input:
this.$emit('input', event.target.value);
},
}
}
</script>
Sources:
https://www.vuemastery.com/conferences/vueconf-us-2018/7-secret-patterns-vue-consultants-dont-want-you-to-know-chris-fritz/
https://zendev.com/2018/05/31/transparent-wrapper-components-in-vue.html