I want to check if child component is mounted and I want to move that information to he parent component. For this I am using emits.
So with example here is my parent component:
<child #is-child-mounted="childMounted" />
export default {
data() {
return {
childMounted: false,
};
},
mounted() {
if (this.childMounted) {
//do something
}
},
}
and in child component, I am changing 'is-child-mounted' to true:
mounted() {
this.$emit('isChildMounted', true);
},
But still if (this.childMounted) comes false. So how can I check in parent component if the child component is mounted?
You can add a listener on the child component fom the parent. It would look like this:
Vue3
<Component
#vnodeMounted="handleMounted"
/>
Vue2
<Component
#hook:mounted="handleMounted"
/>
You can replace the hook name by the lifecycle one you want to listen to ! I guess it should be used sparsely as it is not present in the documentation and thus be an internal API that is not destined to be used directly.
source:
https://github.com/vuejs/core/issues/4345#issuecomment-899082892
https://github.com/vuejs/vue/blob/8d3fce029f20a73d5d0b1ff10cbf6fa73c989e62/src/core/instance/lifecycle.js#L348
Looks like there is a typo in the event name in the child component while triggering the event else code should work fine.
It should be is-child-mounted instead of ischildmounted
It should be #is-child-mounted="childMounted = true" instead of #is-child-mounted="childMounted"
Live Demo :
Vue.component('child', {
props: ['childmsg'],
template: '<p>{{ childmsg }}</p>',
mounted() {
this.$emit('is-child-mounted')
}
});
var app = new Vue({
el: '#app',
data: {
childMounted: false
},
mounted() {
if (this.childMounted) {
console.log('child mounted');
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<child childmsg="This is a child component" #is-child-mounted="childMounted = true"></child>
</div>
Related
I have the main component that containing other components which containing anothers components.
So, I have the click events in these components, but to handle it in my parent component, I need to make $emit call in each nested component.
How to make this process more simple, for example like in React, where I need just pass the function handler into component.
In vue 2.2.3+ you can use provide and inject to pass function from ancestor component to child, like great grandparent to child.
please refer following code
// app.vue
<template>
<div id="app">
<HelloWorld msg="button1" />
<HelloWorld msg="button2" />
<HelloWorld msg="button3" />
count: {{ count }}
</div>
</template>
<script>
import HelloWorld from "./components/HelloWorld";
export default {
name: "App",
provide() {
return {
clickHandler: this.clickHandler,
};
},
data() {
return {
count: 0,
};
},
components: {
HelloWorld,
},
methods: {
clickHandler() {
this.count += 1;
console.log("click received");
},
},
};
</script>
// HelloWorld.vue
<template>
<button #click="clickHandler">{{ msg }}</button>
</template>
<script>
export default {
name: "HelloWorld",
inject: ["clickHandler"],
props: {
msg: String,
},
};
</script>
you can see the same clickHandler function from parent is executed with modifying parents count prop on click of each children.
this clickHandler can be injected directly to any descendent at any level therefore application like
parent > child.1 > child.1.1 > child.1.1.1 > child.1.1.1.1(click)
the child.1.1.1.1 can be injected with clickHandler form parent.
try the code at codesandbox
also refer provide/inject
if you need the same value up in the hierarchy or anywhere in the current module, you should try to use the Vuex(State Management) library.
I am building a dashboard app where users will be able to choose widgets that appear in certain positions. I am doing this using
<component :is="name-of-component">
Its all working well but I want the user to be able to edit the component and emit the changes to the parent. By editing lets say for example 1 component displays a welcome message which the user can change.
Right now I have the following
Dashboard.vue
<template>
<component :is="name-of-component"></component>
</template>
<script>
data () {
return {
name-of-component: 'selected-component-name'
}
}
</script>
In the script is the computed, mounted etc. which I don't think have relevance to the question.
Since Im using component :is Im finding it tricky to pass props and emit changes. In my store I have 2 props for the component (title & subtitle) in an array. I can hardcode :props="welcomeMessage" but I don't want to hard code since Im using :is and position of widgets can change.
Emit is also causing an issue for me. I can, of course, emit by hard coding the call to the component but since Im using :is its not going to work for me.
Heres what is working but I need to make it dynamic as any component :is wan contain any widget. Any ideas?
<component
:is="welcomeMessage"
:props="dashboard.welcomeMessage"
#update-welcomeMessage="welcomeMessage(e)">
</component>
OR
<component
:is="busStops"
:props="dashboard.myBusStop"
#update-busStop="busStop(e)">
</component>
Id like to have the components so that I can pull in the different concerns and have each one be more like this where "name-of-component" could be used to populate the :is, :props and #update:
<component
:is="name-of-component"
:props="dashboard.name-of-component"
#update-name-of-component="name-of-component(e)">
</component>
You can use the v-bind and v-on capabilities, and use computed properties just like you are already doing it. I'll explain myself:
<some-component #some-event="doThis" foo="bar"></some-component>
is the same as writing:
<some-component v-bind="{foo: 'bar'}" v-on="{'some-event': doThis}"></some-component>
That means that you can write computed properties to compute which listeners and attributes you want to use for your dynamic component.
I wrote a complete example on jsFiddle if you want: https://jsfiddle.net/tsc2pmrx/
Template:
<div id="app">
<component :is="componentToUse" v-on="listeners" v-bind="attributes"></component>
</div>
JS:
Vue.component('greeting', {
props: ['name'],
template: '<h1>Welcome {{ name }} !</h1>',
mounted () {
setTimeout(() => {
this.$emit('some-event')
}, 2000)
}
});
Vue.component('other-component', {
template: '<h1>Welcome to Other Component</h1>'
})
// create a new Vue instance and mount it to our div element above with the id of app
var vm = new Vue({
el: '#app',
data: {
componentToUse: 'greeting'
},
methods: {
handleOtherComponentEvent () {
console.log('Hello World from other component listener')
},
handleGreetingComponentEvent () {
console.log('Hello World from greeting component event listener')
}
},
computed: {
listeners () {
if (this.componentToUse === 'greeting') {
return {
'some-event': this.handleOtherComponentEvent
}
} else if (this.componentToUse === 'other-component') {
return {
'some-greeting-event': this.handleGreetingComponentEvent
}
}
return {}
},
attributes () {
if (this.componentToUse === 'greeting') {
return {
'name': 'Hammerbot'
}
}
return {}
}
}
});
Context
In Vue 2.0 the documentation and others clearly indicate that communication from parent to child happens via props.
Question
How does a parent tell its child an event has happened via props?
Should I just watch a prop called event? That doesn't feel right, nor do alternatives ($emit/$on is for child to parent, and a hub model is for distant elements).
Example
I have a parent container and it needs to tell its child container that it's okay to engage certain actions on an API. I need to be able to trigger functions.
Vue 3 Composition API
Create a ref for the child component, assign it in the template, and use the <ref>.value to call the child component directly.
<script setup>
import {ref} from 'vue';
const childComponentRef = ref(null);
function click() {
// `childComponentRef.value` accesses the component instance
childComponentRef.value.doSomething(2.0);
}
</script>
<template>
<div>
<child-component ref="childComponentRef" />
<button #click="click">Click me</button>
</div>
</template>
Couple things to note-
If your child component is using <script setup>, you'll need to declare public methods (e.g. doSomething above) using defineExpose.
If you're using Typescript, details of how to type annotate this are here.
Vue 3 Options API / Vue 2
Give the child component a ref and use $refs to call a method on the child component directly.
html:
<div id="app">
<child-component ref="childComponent"></child-component>
<button #click="click">Click</button>
</div>
javascript:
var ChildComponent = {
template: '<div>{{value}}</div>',
data: function () {
return {
value: 0
};
},
methods: {
setValue: function(value) {
this.value = value;
}
}
}
new Vue({
el: '#app',
components: {
'child-component': ChildComponent
},
methods: {
click: function() {
this.$refs.childComponent.setValue(2.0);
}
}
})
For more info, see Vue 3 docs on component refs or Vue 2 documentation on refs.
What you are describing is a change of state in the parent. You pass that to the child via a prop. As you suggested, you would watch that prop. When the child takes action, it notifies the parent via an emit, and the parent might then change the state again.
var Child = {
template: '<div>{{counter}}</div>',
props: ['canI'],
data: function () {
return {
counter: 0
};
},
watch: {
canI: function () {
if (this.canI) {
++this.counter;
this.$emit('increment');
}
}
}
}
new Vue({
el: '#app',
components: {
'my-component': Child
},
data: {
childState: false
},
methods: {
permitChild: function () {
this.childState = true;
},
lockChild: function () {
this.childState = false;
}
}
})
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.1/vue.js"></script>
<div id="app">
<my-component :can-I="childState" v-on:increment="lockChild"></my-component>
<button #click="permitChild">Go</button>
</div>
If you truly want to pass events to a child, you can do that by creating a bus (which is just a Vue instance) and passing it to the child as a prop.
You can use $emit and $on. Using #RoyJ code:
html:
<div id="app">
<my-component></my-component>
<button #click="click">Click</button>
</div>
javascript:
var Child = {
template: '<div>{{value}}</div>',
data: function () {
return {
value: 0
};
},
methods: {
setValue: function(value) {
this.value = value;
}
},
created: function() {
this.$parent.$on('update', this.setValue);
}
}
new Vue({
el: '#app',
components: {
'my-component': Child
},
methods: {
click: function() {
this.$emit('update', 7);
}
}
})
Running example: https://jsfiddle.net/rjurado/m2spy60r/1/
A simple decoupled way to call methods on child components is by emitting a handler from the child and then invoking it from parent.
var Child = {
template: '<div>{{value}}</div>',
data: function () {
return {
value: 0
};
},
methods: {
setValue(value) {
this.value = value;
}
},
created() {
this.$emit('handler', this.setValue);
}
}
new Vue({
el: '#app',
components: {
'my-component': Child
},
methods: {
setValueHandler(fn) {
this.setter = fn
},
click() {
this.setter(70)
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.17/dist/vue.js"></script>
<div id="app">
<my-component #handler="setValueHandler"></my-component>
<button #click="click">Click</button>
</div>
The parent keeps track of the child handler functions and calls whenever necessary.
Did not like the event-bus approach using $on bindings in the child during create. Why? Subsequent create calls (I'm using vue-router) bind the message handler more than once--leading to multiple responses per message.
The orthodox solution of passing props down from parent to child and putting a property watcher in the child worked a little better. Only problem being that the child can only act on a value transition. Passing the same message multiple times needs some kind of bookkeeping to force a transition so the child can pick up the change.
I've found that if I wrap the message in an array, it will always trigger the child watcher--even if the value remains the same.
Parent:
{
data: function() {
msgChild: null,
},
methods: {
mMessageDoIt: function() {
this.msgChild = ['doIt'];
}
}
...
}
Child:
{
props: ['msgChild'],
watch: {
'msgChild': function(arMsg) {
console.log(arMsg[0]);
}
}
}
HTML:
<parent>
<child v-bind="{ 'msgChild': msgChild }"></child>
</parent>
The below example is self explainatory. where refs and events can be used to call function from and to parent and child.
// PARENT
<template>
<parent>
<child
#onChange="childCallBack"
ref="childRef"
:data="moduleData"
/>
<button #click="callChild">Call Method in child</button>
</parent>
</template>
<script>
export default {
methods: {
callChild() {
this.$refs.childRef.childMethod('Hi from parent');
},
childCallBack(message) {
console.log('message from child', message);
}
}
};
</script>
// CHILD
<template>
<child>
<button #click="callParent">Call Parent</button>
</child>
</template>
<script>
export default {
methods: {
callParent() {
this.$emit('onChange', 'hi from child');
},
childMethod(message) {
console.log('message from parent', message);
}
}
}
</script>
If you have time, use Vuex store for watching variables (aka state) or trigger (aka dispatch) an action directly.
Calling child component in parent
<component :is="my_component" ref="my_comp"></component>
<v-btn #click="$refs.my_comp.alertme"></v-btn>
in Child component
mycomp.vue
methods:{
alertme(){
alert("alert")
}
}
I think we should to have a consideration about the necessity of parent to use the child’s methods.In fact,parents needn’t to concern the method of child,but can treat the child component as a FSA(finite state machine).Parents component to control the state of child component.So the solution to watch the status change or just use the compute function is enough
you can use key to reload child component using key
<component :is="child1" :filter="filter" :key="componentKey"></component>
If you want to reload component with new filter, if button click filter the child component
reloadData() {
this.filter = ['filter1','filter2']
this.componentKey += 1;
},
and use the filter to trigger the function
You can simulate sending event to child by toggling a boolean prop in parent.
Parent code :
...
<child :event="event">
...
export default {
data() {
event: false
},
methods: {
simulateEmitEventToChild() {
this.event = !this.event;
},
handleExample() {
this.simulateEmitEventToChild();
}
}
}
Child code :
export default {
props: {
event: {
type: Boolean
}
},
watch: {
event: function(value) {
console.log("parent event");
}
}
}
Hi I made a boolean value in parent component, and passed it to the child component as a props. it has initialized as false, and after the user view the component, the value will change to true, which means the page has been visited.
I have done some research and followed How to properly pass data from child to parent and parent to child component?
here is my js code:
<script>
export default {
props: {
hasLoad: {
type: Boolean
}
},
data () {
return {
hasLoadModel: this.hasLoad
}
},
created: function() {
console.log(this.hasLoad);
},
beforeDestroy: function() {
this.hasLoadModel = true;
this.hasLoad = true;
console.log(this.hasLoadModel);
console.log(this.hasLoad);
}
}
</script>
and html code
<div v-model="skillLoadModel">..</div>
But I still get
[Vue warn]: 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.
I have tried to change the value at either of beforeDestroy or Destroyed, or do not use v-model, but none of them works. The value has changed after I left the page, but when I reenter the page, the value has reset to default value.
Can someone help me please?
Thanks
Don't change the value of the prop. Have the component emit an event so that the parent can take the appropriate action.
Below is an example of a component that is created when the checkbox is checked, and is destroyed when it gets unchecked. The component emits a "dying" event, and the parent receives it and prints a scream to the console.
new Vue({
el: '#app',
data: {
showIt: true
},
methods: {
scream() {
console.log("Aaarg!");
}
},
components: {
myComponent: {
beforeDestroy: function() {
this.$emit('dying');
}
}
}
});
<script src="//unpkg.com/vue#latest/dist/vue.js"></script>
<div id="app">
<input type="checkbox" v-model="showIt">
<my-component v-if="showIt" hasload="true" #dying="scream" inline-template>
<div>Here I am</div>
</my-component>
</div>
I assume you're trying to communicate to the parent that the child has loaded. In that case, you can pass a function as a prop and simply call it when the child mounts.
Parent HTML:
<child :my-load-fn="loadFn"></child>
Parent JS:
methods: {
loadFn() {
this.childHasLoaded = true
}
}
Child JS:
props: ['myLoadFn'],
mounted() {
this.myLoadFn()
}
I'm using vue, version 2.5.8
I want to reload child component's, or reload parent and then force children components to reload.
I was trying to use this.$forceUpdate() but this is not working.
Do You have any idea how to do this?
Use a :key for the component and reset the key.
See https://michaelnthiessen.com/force-re-render/
Add key to child component, then update the key in parent. Child component will be re-created.
<childComponent :key="childKey"/>
If the children are dynamically created by a v-for or something, you could clear the array and re-assign it, and the children would all be re-created.
To simply have existing components respond to a signal, you want to pass an event bus as a prop, then emit an event to which they will respond. The normal direction of events is up, but it is sometimes appropriate to have them go down.
new Vue({
el: '#app',
data: {
bus: new Vue()
},
components: {
child: {
template: '#child-template',
props: ['bus'],
data() {
return {
value: 0
};
},
methods: {
increment() {
this.value += 1;
},
reset() {
this.value = 0;
}
},
created() {
this.bus.$on('reset', this.reset);
}
}
}
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app">
<child :bus="bus">
</child>
<child :bus="bus">
</child>
<child :bus="bus">
</child>
<button #click="() => bus.$emit('reset')">Reset</button>
</div>
<template id="child-template">
<div>
{{value}} <button #click="increment">More!</button>
</div>
</template>
I'm using directive v-if which is responsible for conditional rendering. It only affects reloading HTML <template> part. Sections created(), computed are not reloaded. As I understand after framework load components reloading it is not possible. We can only re render a <template>.
Rerender example.
I have a Child.vue component code:
<template>
<div v-if="show">
Child content to render
{{ callDuringReRender() }}
</div>
</template>
<script>
export default {
data() {
return {
show: true
}
}
,
methods: {
showComponent() {
this.show = true
},
hideComponent() {
this.show = false
},
callDuringReRender() {
console.log("function recall during rendering")
}
}
}
</script>
In my Parent.vue component I can call child methods and using it's v-if to force the child rerender
<template>
<div>
<input type="button"
value="ReRender the child"
#click="reRenderChildComponent"/>
<child ref="childComponent"></child>
</div>
</template>
<script>
import Child from './Child.vue'
export default {
methods: {
reRenderChildComponent(){
this.$refs.childComponent.hideComponent();
this.$refs.childComponent.showComponent()
}
},
components: {
Child
}
}
</script>
After clicking a button in console You will notice message "function recall during rendering" informing You that component was rerendered.
This example is from the link that #sureshvv shared
import Vue from 'vue';
Vue.forceUpdate();
// Using the component instance
export default {
methods: {
methodThatForcesUpdate() {
// ...
this.$forceUpdate(); // Notice we have to use a $ here
// ...
}
}
}
I've found that when you want the child component to refresh you either need the passed property to be output in the template somewhere or be accessed by a computed property.
<!-- ParentComponent -->
<template>
<child-component :user="userFromParent"></child-component>
</template>
<!-- ChildComponent -->
<template>
<!-- 'updated' fires if property 'user' is used in the child template -->
<p>user: {{ user.name }}
</template>
<script>
export default {
props: {'user'},
data() { return {}; }
computed: {
// Or use a computed property if only accessing it in the script
getUser() {
return this.user;
}
}
}
</script>