(Vue.js 3 Options API) How do I access a child method? - javascript

I need to access a child component's method using Vue.js 3 with Options API. There is an answer at How to access to a child method from the parent in vue.js, but it is for Vue.js 2 and Vue.js 3 but with Composition API.
I still tried this, all in the parent component:
<dropdown-list #update="updateChildComponents"></dropdown-list>
<child-component-1 ref="childComponent1Ref" :url="url"></child-component-1>
<child-component-2 ref="childComponent2Ref" :url="url"></child-component-2>
and
methods: {
updateChildComponents() {
this.$refs.childComponent1Ref.childComponentMethod();
this.$refs.childComponent2Ref.childComponentMethod();
}
}
This actually successfully accesses the method, but I think this may not be the right way.
Secondly, I use a prop in the child component that I update in the parent and use in the child component's method, which updates only after the second event. I think these two may be related.
Child component:
props: ['url'],
methods: {
childComponentMethod() {
console.log(this.url); // can access the value from the previous event
}
}
I appreciate any help.

For communication between the parent and the children you should trasfer the value with props. In case the value is changing in the parent you must add watch.
It called 1 way binding because the parent cant see the changes in the child component.
Parent -> child = use props.
Child -> parent = use emits and on event.
<script>
import { reactive,watch, computed,onMounted } from "vue";
export default {
components: {
},
props: { metadata: String },
emits: [""],
setup(props) {
onMounted(async () => {
//first initilize
if (props.metadata) {
state.metadataName = props.metadata;
}
});
//track after the changes in the parent
watch(
() => props.metadata,
async (metadata) => {
if (metadata) {
}
}
);
return {
};
},
};
</script>

Related

get id value of url in another component passed via props - vue

I am creating one reusable component. There are two child components. This flow is like below
Child component 1 -> Parent Component -> Super Parent main Component
In child component, i am creating a prop url then pass into Parent component then pass to Super Parent component where i am passing value like this below.
Child Component
prop: {
urls: {
type: Object,
required: true,
default: () => ({
saveProduct: '/entity/save',
updateProduct: '/entity/update
})
}
}
Parent Component
<ChildComponent :urls = "uris" />
props: {
uris: {
type:Object,
required:true,
default: () => ({})
}
}
Super Parent Component
<ParentComponent :uris="urls" />
data() {
return {
urls: {
saveUri: `/products/${this.$route.params.id}/categories`,
updateUri: `/products/${this.$route.params.id}/categories/${this.productId}`
}
}
}
Here i am giving snippets for flow not full code. I want to know the generic way to get the productId value in Super parent.
In here, i can get this (this.$route.params.id) value but how can i get productid value available in super parent from Child component.
Any generic example will be helpful for me... How to send data from one component to next of next component?
Props are for passing data downwards from parent to child. To send data upwards from child to parent, emit and event from child and listen to it in parent.
this.$emit('clicked', 'someValue')
Another option would be using a global state store like Vuex.

Performance: Dispatching an action vs passing as props in React

I have a technical question. I am trying to pass a value from child component to store by using action dispatcher inside my child component. This action dispatcher then updates the state value in the reducer.
Is it advisable to pass value from the child component this way? will it affect the performance of the react app?
Or should I use props to pass from child to parent component and then update the state.
Please advise as I searched a lot about this but didn't get any info.
Problem with passing dispatcher to your child is your child component is not very reusable. I would suggest to pass a callback method to your child which contains the logic of dispatching the event.
Parent:
class ParentComponent extends React.Component {
loginHandler(){
...
this.props.someMethod();
}
render() {
return {
...
<ChildComponent click="loginHandler"></ChildComponent>
...
}
}
}
const mapDispatchToProps = dispatch => {
return {
// dispatching plain actions
...
someMethod: () => dispatch({ ... }),
...
}
}
export default connect(null, mapDispatchToProps)(ParentComponent);
Child Component:
function ChildComponent({click}) {
return {
...
<button click={click}></button>
...
}
}
Now with this approach your child approach doesn't carry any business logic. It can be used at multiple places.

Unable to overwrite method in Vue constructor

I have a component with one method, which I'm firing on creation. It's using vue-select but purpose of this component shouldn't be relevant to my issue.
<template>
<v-select :on-change="onchangecallback"></v-select>
</template>
<script>
import Vue from 'vue'
import vSelect from 'vue-select'
Vue.component('v-select', vSelect);
export default {
methods: {
onchangecallback: () => {alert('default')}
},
created: function() {
this.onchangecallback();
}
}
</script>
In other file I'm importing this component and creating a new instance of it with Vue constructor and passing new onchangecallback method, which, by my understanding, should overwrite the default onchangecallback method:
import VSelect from './components/ui/VSelect.vue';
new Vue({
VSelect,
el: '#app',
components: {VSelect},
template: `<v-select />`,
methods: {
onchangecallback: () => {alert('custom')} // doesn't work
}
});
But when I start the app, instead of alert('custom') I still get alert('default').
I don't know what you are trying to achieve.
But here is my solution https://codesandbox.io/s/84qw9z13v9
You need to define a prop to pass your new callback function to that component (through the prop)
props: {
onchangecallback: {
type: Function,
default() {
return function() {
alert('default');
};
},
},
},
created: function() {
this.onchangecallback();
}
And the use it instead the default one.
Check all the code in that snippet.
For communication between components you're supposed to use events. Emit an event in a child component and make the parent component listen to it:
In the child component:
created() {
this.$emit('change')
}
In the parent component:
Template:
<child-component v-on:change="doSomething" />
Methods:
methods: {
doSomething() {
// ...
}
}
Explanation
In the child component you emit an event, in this case "change", whenever something changed. In your case this was upon creation of the component.
In the parent component you tell Vue that, whenever the child component emits a "change" event, it should run the method "doSomething" in your parent component.
This is used in many places, i.e. inputs, where the input emits an event "input" whenever its content changes and any parent can listen for that by using v-on:input="methodHere".

Child component to use parent function in vue js

I have a method initialized within the parent component called setMessage() and I'd like to be able to call it within the child component.
main.js
const messageBoard = new Vue({
el: '#message-board',
render: h => h(App),
})
App (App.vue (parent))..
export default {
data() {
return { messages: state }
},
methods: {
setMessage(message) {
console.log(message);
}
},
template: `
<div>
<child-component></child-component>
</div>
`,
}
child
const child = Vue.extend({
mounted() {
// attempting to use this function from the parent
this.$dispatch('setMessage', 'HEY THIS IS MY MESSAGE!');
}
});
Vue.component('child-component', child);
Right now I'm getting this.$dispatch is not a function error message. What am I doing wrong? How can I make use of parent functions in various child components? I've also tried $emit, it doesn't throw an error & it doesn't hit the function.
Thank you for your help in advance!
You have a couple options.
Option 1 - referencing $parent from child
The simplest is to use this.$parent from your child component. Something like this:
const Child = Vue.extend({
mounted() {
this.$parent.setMessage("child component mounted");
}
})
Option 2 - emitting an event and handling in parent
But that strongly couples the child to its parent. To fix this, you could $emit an event in the child and have the parent handle it. Like this:
const ChildComponent = Vue.extend({
mounted() {
this.$emit("message", "child component mounted (emitted)");
}
})
// in the parent component template
<child-component #message="setMessage"></child-component>
Option 3 - central event bus
One last option, if your components don't have a direct parent-child relationship, is to use a separate Vue instance as a central event bus as described in the Guide. It would look something like this:
const bus = new Vue({});
const ChildComponent = Vue.extend({
mounted() {
bus.$emit("message-bus", "child component mounted (on the bus)");
}
})
const app = new Vue({
...
methods: {
setMessage(message) {
console.log(message);
}
},
created() {
bus.$on('message-bus', this.setMessage)
},
destroyed() {
bus.$off('message-bus', this.setMessage)
}
});
Update (Option 2a) - passing setMessage as a prop
To follow up on your comment, here's how it might work to pass setMessage to the child component as a prop:
const ChildComponent = Vue.extend({
props: ["messageHandler"],
mounted() {
this.messageHandler('from message handler');
}
})
// parent template (note the naming of the prop)
<child-component :message-handler="setMessage"></child-component>
// parent component providing 'foo'
var Provider = {
methods: {
foo() {
console.log('foo');
},
},
provide: {
foo: this.foo,
},
}
// child component injecting 'foo'
var Child = {
inject: ['foo'],
created() {
this.foo() // => "foo";
},
}

vuejs update parent data from child component

I'm starting to play with vuejs (2.0).
I built a simple page with one component in it.
The page has one Vue instance with data.
On that page I registered and added the component to html.
The component has one input[type=text]. I want that value to reflect on the parent (main Vue instance).
How do I correctly update the component's parent data?
Passing a bound prop from the parent is not good and throws some warnings to the console. They have something in their doc but it is not working.
Two-way binding has been deprecated in Vue 2.0 in favor of using a more event-driven architecture. In general, a child should not mutate its props. Rather, it should $emit events and let the parent respond to those events.
In your specific case, you could use a custom component with v-model. This is a special syntax which allows for something close to two-way binding, but is actually a shorthand for the event-driven architecture described above. You can read about it here -> https://v2.vuejs.org/v2/guide/components.html#Form-Input-Components-using-Custom-Events.
Here's a simple example:
Vue.component('child', {
template: '#child',
//The child has a prop named 'value'. v-model will automatically bind to this prop
props: ['value'],
methods: {
updateValue: function (value) {
this.$emit('input', value);
}
}
});
new Vue({
el: '#app',
data: {
parentValue: 'hello'
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<div id="app">
<p>Parent value: {{parentValue}}</p>
<child v-model="parentValue"></child>
</div>
<template id="child">
<input type="text" v-bind:value="value" v-on:input="updateValue($event.target.value)">
</template>
The docs state that
<custom-input v-bind:value="something" v-on:input="something = arguments[0]"></custom-input>
is equivalent to
<custom-input v-model="something"></custom-input>
That is why the prop on the child needs to be named value, and why the child needs to $emit an event named input.
In child component:
this.$emit('eventname', this.variable)
In parent component:
<component #eventname="updateparent"></component>
methods: {
updateparent(variable) {
this.parentvariable = variable
}
}
From the documentation:
In Vue.js, the parent-child component relationship can be summarized as props down, events up. The parent passes data down to the child via props, and the child sends messages to the parent via events. Let’s see how they work next.
How to pass props
Following is the code to pass props to a child element:
<div>
<input v-model="parentMsg">
<br>
<child v-bind:my-message="parentMsg"></child>
</div>
How to emit event
HTML:
<div id="counter-event-example">
<p>{{ total }}</p>
<button-counter v-on:increment="incrementTotal"></button-counter>
<button-counter v-on:increment="incrementTotal"></button-counter>
</div>
JS:
Vue.component('button-counter', {
template: '<button v-on:click="increment">{{ counter }}</button>',
data: function () {
return {
counter: 0
}
},
methods: {
increment: function () {
this.counter += 1
this.$emit('increment')
}
},
})
new Vue({
el: '#counter-event-example',
data: {
total: 0
},
methods: {
incrementTotal: function () {
this.total += 1
}
}
})
Child Component
Use this.$emit('event_name') to send an event to the parent component.
Parent Component
In order to listen to that event in the parent component, we do v-on:event_name and a method (ex. handleChange) that we want to execute on that event occurs
Done :)
I agree with the event emitting and v-model answers for those above. However, I thought I would post what I found about components with multiple form elements that want to emit back to their parent since this seems one of the first articles returned by google.
I know the question specifies a single input, but this seemed the closest match and might save people some time with similar vue components. Also, no one has mentioned the .sync modifier yet.
As far as I know, the v-model solution is only suited to one input returning to their parent. I took a bit of time looking for it but Vue (2.3.0) documentation does show how to sync multiple props sent into the component back to the parent (via emit of course).
It is appropriately called the .sync modifier.
Here is what the documentation says:
In some cases, we may need “two-way binding” for a prop.
Unfortunately, true two-way binding can create maintenance issues,
because child components can mutate the parent without the source of
that mutation being obvious in both the parent and the child.
That’s why instead, we recommend emitting events in the pattern of
update:myPropName. For example, in a hypothetical component with a
title prop, we could communicate the intent of assigning a new value
with:
this.$emit('update:title', newTitle)
Then the parent can listen to
that event and update a local data property, if it wants to. For
example:
<text-document
v-bind:title="doc.title"
v-on:update:title="doc.title = $event"
></text-document>
For convenience, we offer a shorthand for this pattern with the .sync modifier:
<text-document v-bind:title.sync="doc.title"></text-document>
You can also sync multiple at a time by sending through an object. Check out the documentation here
The way more simple is use this.$emit
Father.vue
<template>
<div>
<h1>{{ message }}</h1>
<child v-on:listenerChild="listenerChild"/>
</div>
</template>
<script>
import Child from "./Child";
export default {
name: "Father",
data() {
return {
message: "Where are you, my Child?"
};
},
components: {
Child
},
methods: {
listenerChild(reply) {
this.message = reply;
}
}
};
</script>
Child.vue
<template>
<div>
<button #click="replyDaddy">Reply Daddy</button>
</div>
</template>
<script>
export default {
name: "Child",
methods: {
replyDaddy() {
this.$emit("listenerChild", "I'm here my Daddy!");
}
}
};
</script>
My full example: https://codesandbox.io/s/update-parent-property-ufj4b
It is also possible to pass props as Object or Array. In this case data will be two-way binded:
(This is noted at the end of topic: https://v2.vuejs.org/v2/guide/components.html#One-Way-Data-Flow )
Vue.component('child', {
template: '#child',
props: {post: Object},
methods: {
updateValue: function () {
this.$emit('changed');
}
}
});
new Vue({
el: '#app',
data: {
post: {msg: 'hello'},
changed: false
},
methods: {
saveChanges() {
this.changed = true;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<div id="app">
<p>Parent value: {{post.msg}}</p>
<p v-if="changed == true">Parent msg: Data been changed - received signal from child!</p>
<child :post="post" v-on:changed="saveChanges"></child>
</div>
<template id="child">
<input type="text" v-model="post.msg" v-on:input="updateValue()">
</template>
In Parent Conponent -->
data : function(){
return {
siteEntered : false,
};
},
In Child Component -->
this.$parent.$data.siteEntered = true;
2021 ANSWER - Vue 2.3+
SHORT ANSWER: Just add .sync modifier in the parent and pass the data as props to the children:
// PARENT:
data () {
return {
formData: {
members: [] //<- we wanna pass this one down to children and add/remove from the child component
}
}
// PARENT TEMPLATE:
<!-- ADD MEMBERS -->
<add-members :members.sync="formData.members" />
Nested child component: AddMembers.vue
export default {
name: 'AddMembers',
props: ['members'],
methods: {
addMember () {
this.members.push(new Member()) // <-- you can play and reactivity will work (in the parent)
},
removeMember (index) {
console.log('remove', index, this.members.length < 1)
this.members.splice(index, 1)
}
}
}
Long story: changes from the child component in reallity are being $emitted and updating formData.members[] of the parent.
source: Mauro Perez at medium
In the child
<input
type="number"
class="form-control"
id="phoneNumber"
placeholder
v-model="contact_number"
v-on:input="(event) => this.$emit('phoneNumber', event.target.value)"
/>
data(){
return {
contact_number : this.contact_number_props
}
},
props : ['contact_number_props']
In parent
<contact-component v-on:phoneNumber="eventPhoneNumber" :contact_number_props="contact_number"></contact-component>
methods : {
eventPhoneNumber (value) {
this.contact_number = value
}
The correct way is to $emit() an event in the child component that the main Vue instance listens for.
// Child.js
Vue.component('child', {
methods: {
notifyParent: function() {
this.$emit('my-event', 42);
}
}
});
// Parent.js
Vue.component('parent', {
template: '<child v-on:my-event="onEvent($event)"></child>',
methods: {
onEvent: function(ev) {
v; // 42
}
}
});
When we want to pass the data to the parent component as well as another nested child component of the current child component, using a data property would be useful as shown in the following example.
Example:
Calling your child component from the parent component like this.
Parent component:
<template>
<TodoItem :todoParent="todo" />
</template>
<script>
export default {
data() {
return {
todo: {
id:1,
task:'todo 1',
completed:false
}
};
}
}
</script>
Child component:
<template>
<div class="todo-item" v-bind:class="{'is-completed':todo.completed}">
<p>
<input type="checkbox" #change="markCompleted" />
{{todo.task}}
<button class="del">x</button>
</p>
</div>
</template>
<script>
export default {
name: "TodoItem",
props: ["todoParent"],
data() {
return {
todo: this.todoParent,
};
},
methods: {
markCompleted() {
this.todo.completed = true
},
},
};
</script>
Even you can pass this property to the nested child component and it won't give this error/warning.
Other use cases when you only need this property sync between parent and child component. It can be achieved using the sync modifier from Vue. v-model can also be useful. Many other examples are available in this question thread.
Example2: using component events.
We can emit the event from the child component as below.
Parent component:
<template>
<TodoItem :todo="todo" #markCompletedParent="markCompleted" />
</template>
<script>
export default {
data() {
return {
todo: {
id:1,
task:'todo 1',
completed:false
}
};
},
methods: {
markCompleted() {
this.todo.completed = true
},
}
}
</script>
Child component:
<template>
<div class="todo-item" v-bind:class="{'is-completed':todo.completed}">
<p>
<input type="checkbox" #change="markCompleted" />
{{todo.task}}
<button class="del">x</button>
</p>
</div>
</template>
<script>
export default {
name: "TodoItem",
props: ["todo"],
methods: {
markCompleted() {
this.$emit('markCompletedParent', true)
},
}
};
</script>
Another way is to pass a reference of your setter from the parent as a prop to the child component, similar to how they do it in React.
Say, you have a method updateValue on the parent to update the value, you could instantiate the child component like so: <child :updateValue="updateValue"></child>. Then on the child you will have a corresponding prop: props: {updateValue: Function}, and in the template call the method when the input changes: <input #input="updateValue($event.target.value)">.
I don't know why, but I just successfully updated parent data with using data as object, :set & computed
Parent.vue
<!-- check inventory status - component -->
<CheckInventory :inventory="inventory"></CheckInventory>
data() {
return {
inventory: {
status: null
},
}
},
Child.vue
<div :set="checkInventory">
props: ['inventory'],
computed: {
checkInventory() {
this.inventory.status = "Out of stock";
return this.inventory.status;
},
}
his example will tell you how to pass input value to parent on submit button.
First define eventBus as new Vue.
//main.js
import Vue from 'vue';
export const eventBus = new Vue();
Pass your input value via Emit.
//Sender Page
import { eventBus } from "../main";
methods: {
//passing data via eventbus
resetSegmentbtn: function(InputValue) {
eventBus.$emit("resetAllSegment", InputValue);
}
}
//Receiver Page
import { eventBus } from "../main";
created() {
eventBus.$on("resetAllSegment", data => {
console.log(data);//fetching data
});
}
I think this will do the trick:
#change="$emit(variable)"
Intro
I was looking for sending data from parent to child (and back) in vue3 (I know the question was about vue2, but there are no references for vue3 on SO at the time).
Below is the working boilerplate result, pure "html + js", no packagers, modules, etc with few caveats I had, explained.
Notes:
Tnserting the child - line
<component-a :foo="bar" #newfooevent="bar = $event"></component-a>`
I bind parent.bar to child.foo using short-hand :foo="bar", same as v-bind:foo="bar". It passes data from parent to child through props.
Caveat: Event listener should be placed in the child component tag only!
That is the #newfooevent="bar = $event" part.
You cannot catch the signal in the <div id="app"> or anywhere else inside the parent.
Still, this is the parent's side of the universe, and here you can access all parent's data and extract the data from the child's signal to deal with it.
You can create app, and define component after it (the app.component("component-a", ...) part.
Caveat: there are no need in forward declaration of components, e.g. functions in C/C++. You can create app which uses the component, and define the component afterwards. I lost a lot of time looking for the way to declare it somehow - no need.
Here you can find a nice example of the v-model usage, and the code I used to sort things out: https://javascript.plainenglish.io/vue-3-custom-events-d2f310fe34c9
The example
<!DOCTYPE html>
<html lang="en">
<head>
<title>App</title>
<meta charset="utf-8" />
<script src="https://unpkg.com/vue#next"></script>
</head>
<body>
<div id="app">
<component-a :foo="bar" #newfooevent="bar = $event"></component-a>
<p>Parent copy of `bar`: {{ bar }}</p>
<button #click="bar=''">Clear</button>
</div>
<script>
const app = Vue.createApp({
data() {
return {
bar: "bar start value"
};
}
});
app.component("component-a", {
props: {
foo: String
},
template: `
<input
type="text"
:value="foo"
#input="$emit('newfooevent', $event.target.value)">
`
});
app.mount("#app");
</script>
</body>
</html>
There is another way of communicating data change from child to parent which uses provide-inject method. Parent component "provides" data or method for the child component, and this data or method is then "injected" into child component - but it can also be used for triggering a method in parent and passing it a parameter.
This approach can be especially useful when having a child component which happens to be embedded in multiple other components. Also, in a large project care must be taken not to lose overview of provide and inject usage.
Example of parent (top level) component App.vue using provide to give access to it's method updateParentValue (if method is provided and not data, provide is in form of a method):
<template>
<h2>App.vue, parentValue is: <em>{{ parentValue }}</em></h2>
<ChildComponent1 />
</template>
<script>
import ChildComponent1 from "./components/ChildComponent1.vue";
export default {
data() {
return {
parentValue: "",
};
},
components: {
ChildComponent1,
},
provide() {
return {
updateParent: this.updateParentValue,
};
},
methods: {
updateParentValue($value) {
this.parentValue = $value;
},
},
};
</script>
In this example component Component4.vue is in the "bottom", that is, App.vue contains Component1, Component1 contains Component2... until Component4 which actually utilizes inject to get access to parent method which is then invoked and a parameter $value is passed (just a random number here):
<template>
<div>
<h2>ChildComponent4.vue</h2>
<button #click="updateParent(Math.random())">
Update parent value in App.vue
</button>
</div>
</template>
<script>
export default {
inject: ["updateParent"],
};
</script>
Entire example is available here.
Vue.js documentation

Categories

Resources