Creating/Destroying the Vue Component based on text search - javascript

I have the following in App.vue
<template>
<div id="app">
<input type="text" v-model="term">
<hello-world text="Button 1" v-if="term === ''"></hello-world>
<hello-world v-else text="Button 2"></hello-world>
</div>
</template>
<script>
import HelloWorld from '#/components/HelloWorld'
export default {
name: 'app',
data() {
return {
term: ''
}
},
components: {
HelloWorld
}
}
</script>
And here's the HelloWorld.vue:
<template>
<div>
<button>{{ text }}</button>
</div>
</template>
<script>
export default {
props: {
text: String
},
created() {
console.log('Created')
},
destroyed() {
console.log('Destroyed')
}
}
</script>
So, when I type something the first component should be destroyed and the second component should be created. However, nothing like that happens. The component neither gets destroyed nor gets created.
It's as if the v-if didn't trigger the created() & destroyed() function. Please help me with this.

Vue uses virtual dom approach. So, it is comparing the virtual tree and it is not identifying changes on structure (oldNode.type === newNode.type). When it occurs, Vue updates the same component instead of destroying the old node and creating a new one.
Try to force Vue to detect virtual tree changes avoiding use siblings with the same tag name and controlled by v-if directive.
Reference:
https://medium.com/#deathmood/how-to-write-your-own-virtual-dom-ee74acc13060
Vue.component('hello-world', {
props: {
text: String
},
created() {
console.log('Created')
},
destroyed() {
console.log('Destroyed')
},
template: "<button>{{ text }}</button>"
});
var app = new Vue({
el: "#app",
data() {
return {
term: ''
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input type="text" v-model="term">
<span><hello-world v-if="!term" text="Button 1"></hello-world></span>
<span><hello-world v-if="term" text="Button 2"></hello-world></span>
</div>

I am not sure what you are trying to achieve, but testing your code logs created from both components
https://codesandbox.io/s/8l0j43zy89
Since you are actually showing conditionally the same component, I don't think it will get destroyed.

Related

Mixin for destroyed Vue component is still listening for events

I have a parent component that conditionally renders one of two child components:
<template>
<div>
<!-- other code that changes conditional rendering -->
<folders v-if="isSearchingInFolders" :key="1234"></folders>
<snippets v-if="!isSearchingInFolders" :key="5678"></snippets>
</div>
</template>
Each of these components use the same mixin (searchMixin) locally like so:
<template>
<div>
<div>
<snippet
v-for="item in items"
:snippet="item"
:key="item.id">
</snippet>
<img v-if="busy" src="/icons/loader-grey.svg" width="50">
</div>
<button #click="getItems">Get More</button>
</div>
</template>
<script>
import searchMixin from './mixins/searchMixin';
import Snippet from './snippet';
export default {
components: { Snippet },
mixins: [searchMixin],
data() {
return {
resourceName: 'snippets'
}
},
}
</script>
Each of the components is functionally equivalent with some slightly different markup, so for the purposes of this example Folders can be substituted with Snippets and vice versa.
The mixin I am using looks like this (simplified):
import axios from 'axios'
import { EventBus } from '../event-bus';
export default {
data() {
return {
hasMoreItems: true,
busy: false,
items: []
}
},
created() {
EventBus.$on('search', this.getItems)
this.getItems();
},
destroyed() {
this.$store.commit('resetSearchParams')
},
computed: {
endpoint() {
return `/${this.resourceName}/search`
},
busyOrMaximum() {
return this.busy || !this.hasMoreItems;
}
},
methods: {
getItems(reset = false) {
<!-- get the items and add them to this.items -->
}
}
}
In the parent component when I toggle the rendering by changing the isSearchingInFolders variable the expected component is destroyed and removed from the DOM (I have checked this by logging from the destroyed() lifecycle hook. However the searchMixin that was included in that component does not appear to be destroyed and still appears to listen for events. This means that when the EventBus.$on('search', this.getItems) line is triggered after changing which component is actively rendered from the parent, this.getItems() is triggered twice. Once for folders and once for snippets!
I was expecting the mixins for components to be destroyed along with the components themselves. Have I misunderstood how component destruction works?
Yes, when you pass an event handler as you do EventBus keeps the reference to the function you passed into. That prevents the destruction of the component object. So you need clear the reference by calling EventBus.$off so that the component can be destructed. So your destroy event hook should look like this:
destroyed() {
this.$store.commit('resetSearchParams')
EventBus.$off('search', this.getItems)
},

How to call/initlialize a vue method from outside of the Vue APP

I have an app that is mounted within the page of a preexisting website. In order to initialize the app i have a button within my Vue app to toggle/start the actual Vue logic.
It is all very straight forward, a button appears on the page, click it, the app logic and methods all come to life.
<template>
<button #click.prevent="toggle">Click me</button>
</template>
<script>
export default {
computed: {
isBurgerActive() {
return this.$store.getters.getIsNavOpen;
}
},
methods: {
toggle() { <----- CALL THIS METHOD OUTSIDE OF VUE
this.$store.dispatch('toggleNav');
this.$store.dispatch('getProduct');
}
}
}
</script>
What i want to do is initialize this app with a button that is not within the Vue app. Essentially saying on click of button outside of the Vue app, initialize the toggle() method and start the whole process off.
Is that possible?
If you assign the component to a variable. You can call the methods on that variable. In fact, you can access other properties of vue from that variable (ex: refs, data).
Try the snipet below:
var app = new Vue({
el: "#app",
data() {
return {
isActive: false,
}
},
computed: {
isBurgerActive() {
return this.isActive ? 'active':'inactive'
}
},
methods: {
toggle() {
this.isActive = !this.isActive;
}
},
})
document.getElementById('btn').addEventListener("click", function() {
app.toggle();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div>
<button id="btn">
Click Me
</button>
</div>
<div id="app">
<h2>Active: {{ isBurgerActive }}</h2>
</div>

Change a property's value in one component from within another component

I'm trying to wrap my head around hoe Vue.js works, reading lots of documents and tutorials and taking some pluralsight classes. I have a very basic website UI up and running. Here's the App.vue (which I'm using kinda as a master page).
(To make reading this easier and faster, look for this comment: This is the part you should pay attention to)...
<template>
<div id="app">
<div>
<div>
<CommandBar />
</div>
<div>
<Navigation />
</div>
</div>
<div id="lowerContent">
<!-- This is the part you should pay attention to -->
<template v-if="showLeftContent">
<div id="leftPane">
<div id="leftContent">
<router-view name="LeftSideBar"></router-view>
</div>
</div>
</template>
<!-- // This is the part you should pay attention to -->
<div id="mainPane">
<div id="mainContent">
<router-view name="MainContent"></router-view>
</div>
</div>
</div>
</div>
</template>
And then in the same App.vue file, here's the script portion
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import CommandBar from './components/CommandBar.vue';
import Navigation from './components/Navigation.vue';
#Component({
components: {
CommandBar,
Navigation,
}
})
export default class App extends Vue {
data() {
return {
showLeftContent: true // <--- This is the part you should pay attention to
}
}
}
</script>
Ok, so the idea is, one some pages I want to show a left sidebar, but on other pages I don't. That's why that div is wrapped in <template v-if="showLeftContent">.
Then with the named <router-view>'s I can control which components get loaded into them in the `router\index.ts\ file. The routes look like this:
{
path: '/home',
name: 'Home',
components: {
default: Home,
MainContent: Home, // load the Home compliment the main content
LeftSideBar: UserSearch // load the UserSearch component in the left side bar area
}
},
So far so good! But here's the kicker. Some pages won't have a left side bar, and on those pages, I want to change showLeftContent from true to false. That's the part I can't figure out.
Let's say we have a "Notes" component that looks like this.
<template>
<div class="notes">
Notes
</div>
</template>
<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
#Component
export default class Notes extends Vue {
data() {
return {
showLeftContent: false // DOES NOT WORK
}
}
}
</script>
Obviously, I'm not handling showLeftContent properly here. It would seem as if the properties in data are scoped only to that component, which I understand. I'm just not finding anything on how I can set a data property in the App component and then change it in a child component when that child is loaded through a router-view.
Thanks!
EDIT:
I changed the script section of the Notes component from:
<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
#Component
export default class Notes extends Vue {
data() {
return {
showLeftContent: false // DOES NOT WORK
}
}
}
</script>
to:
<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
#Component
export default class Notes extends Vue {
mounted() {
this.$root.$data.showLeftContent = false;
}
}
</script>
And while that didn't cause any compile or runtime errors, it also didn't have the desired effect. On Notes, the left side bar still shows.
EDIT 2:
If I put an alert in the script section of the Notes component:
export default class Notes extends Vue {
mounted() {
alert(this.$root.$data.showLeftContent);
//this.$root.$data.showLeftContent = false;
}
}
The alert does not pop until I click on "Notes" in the navigation. But, the value is "undefined".
EDIT 3:
Struggling with the syntax here (keep in mind this is TypeScript, which I don't know very well!!)
Edit 4:
Inching along!
export default class App extends Vue {
data() {
return {
showLeftContent: true
}
}
leftContent(value: boolean) {
alert('clicked');
this.$root.$emit('left-content', value);
}
}
This does not result in any errors, but it also doesn't work. The event never gets fired. I'm going to try putting it in the Navigation component and see if that works.
As it says on #lukebearden answer you can use the emit event to pass true/false to the main App component on router-link click.
Assuming your Navigation component looks like below, you can do something like that:
#Navigation.vue
<template>
<div>
<router-link to="/home" #click.native="leftContent(true)">Home</router-link> -
<router-link to="/notes" #click.native="leftContent(false)">Notes</router-link>
</div>
</template>
<script>
export default {
methods: {
leftContent(value) {
this.$emit('left-content', value)
}
}
}
</script>
And in your main App you listen the emit on Navigation:
<template>
<div id="app">
<div>
<Navigation #left-content="leftContent" />
</div>
<div id="lowerContent">
<template v-if="showLeftContent">
//...
</template>
<div id="mainPane">
//...
</div>
</div>
</div>
</template>
<script>
//...
data() {
return {
showLeftContent: true
}
},
methods: {
leftContent(value) {
this.showLeftContent = value
}
}
};
</script>
A basic approach in a parent-child component relationship is to emit events from the child and then listen and handle that event in the parent component.
However, I'm not sure that approach works when working with the router-view. This person solved it by watching the $route attribute for changes. https://forum.vuejs.org/t/emitting-events-from-vue-router/10136/6
You might also want to look into creating a simple event bus using a vue instance, or using vuex.
If you'd like to access the data property (or props, options etc) of the root instance, you can use this.$root.$data. (Check Vue Guide: Handling Edge)
For your codes, you can change this.$root.$data.showLeftContent to true/false in the hook=mounted of other Components, then when Vue creates instances for those components, it will show/hide the left side panel relevantly.
Below is one demo:
Vue.config.productionTip = false
Vue.component('child', {
template: `<div :style="{'background-color':color}" style="padding: 10px">
Reach to root: <button #click="changeRootData()">Click me!</button>
<hr>
<slot></slot>
</div>`,
props: ['color'],
methods: {
changeRootData() {
this.$root.$data.testValue += ' :) '
}
}
})
new Vue({
el: '#app',
data() {
return {
testValue: 'Puss In Boots'
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
<h2>{{testValue}}</h2>
<child color="red"><child color="gray"><child color="green"></child></child></child>
</div>

How do I use data from Vue.js child component within parent component?

I have a form component where I use a child component. I want to use data from the child component within the parent.
My component in html:
<candidates-form endpoint='/candidates/create' buttontext='Add Candidate'></candidates-form>
Then here is the Vue instance:
CandidatesForm.vue
<template>
<div class='row'>
<div class='form-group'>
<label>Name:</label>
<input type='text' class='form-control' v-model='name'>
</div>
<div class='form-group'>
<location-input></location-input>
</div>
<button class='btn btn-primary'>{{buttontext}}</button>
</div>
</template>
<script>
export default {
data() {
return {}
},
props: ['endpoint', 'buttontext'],
ready() {}
}
</script>
I utilize the locationInput component in there and it renders to the screen nicely. That component implements Google Maps typeahead functionality for the input field and looks like this:
LocationInput.vue
<template>
<place-input
:place.sync="placeInput.place"
:types.sync="placeInput.types"
:component-restrictions.sync="placeInput.restrictions"
class='form-control'
label='Location: '
name='location'
></place-input>
<pre>{{ placeInput.place | json }}</pre>
</template>
<script>
import { PlaceInput, Map } from 'vue-google-maps'
export default {
data() {
return {
placeInput: {
place: {
name: ''
},
types: [],
restrictions: {'country': 'usa'}
}
}
},
props: ['location'],
components: {
PlaceInput
},
ready() {
}
}
</script>
<style>
label { display: block; }
</style>
I want to submit the name value and information from placeInput.place to the server.
I register both components in my main app file like so:
Vue.component('locationInput', require('./components/LocationInput.vue'));
Vue.component('candidatesForm', require('./components/CandidatesForm.vue'));
const app = new Vue({
el: 'body'
});
How do I pass the placeInput.place data from location-input component to candidates-form component?
I want to send the placeInput.place and name data from the candidates-form component to the server, most likely using vue-resource.
Hey no need for a store or Vuex. Pass data using props!
Final solution:
Blade template:
#extends('layouts.app')
#section('content')
<div class='col-md-6 col-md-offset-3'>
<h1>Add New Candidate</h1>
<hr>
<candidates-form endpoint='/candidates/create' buttontext='Add Candidate'></candidates-form>
</div>
#stop
Parent Vue component:
<template>
<div>
<div class='form-group'>
<label>Name:</label>
<input type='text' class='form-control' v-model='name'>
</div>
<div class='form-group'>
<location-input :location="locationData"></location-input>
</div>
<button class='btn btn-primary'>{{buttontext}}</button>
<pre>{{ locationData | json }}</pre>
</div>
</template>
<script>
export default {
data() {
return {
locationData: {
place: {
name: ''
},
types: [],
restrictions: {'country': 'usa'}
}
}
},
props: ['endpoint', 'buttontext']
}
</script>
Child Vue component:
<template>
<place-input
:place.sync="location.place"
:types.sync="location.types"
:component-restrictions.sync="location.restrictions"
class='form-control'
label='Location: '
name='location'
></place-input>
</template>
<script>
import { PlaceInput, Map } from 'vue-google-maps'
export default {
props: ['location'],
components: {
PlaceInput
}
}
</script>
<style>
label { display: block; }
</style>
Aaaaand the overall app.js file (this is within a Laravel 5.3 app btw)
import { load } from 'vue-google-maps'
load({
key: '<API_KEY>',
v: '3.24', // Google Maps API version
libraries: 'places', // for places input
});
Vue.component('locationInput', require('./components/LocationInput.vue'));
Vue.component('candidatesForm', require('./components/CandidatesForm.vue'));
Vue.component('company-list', require('./components/CompanyList.vue'));
const app = new Vue({
el: 'body'
});
This article from alligator.io also helped simplify things for me also. I was overthinking it!
Shout out to #GuillaumeLeclerc for the vue-google-maps component: https://github.com/GuillaumeLeclerc/vue-google-maps
Check out my answer here VueJS access child component's data from parent , pretty same questions.
If you are working with large scale application, the best option is to use Vuex, it would save you from a lot of troubles.
Otherwise if it's not a bug app, then you can go with my approach, or using Event Bus.
I would recommend the data store approach which is in the VueJS documentation here: https://v2.vuejs.org/v2/guide/state-management.html
Essentially you would have a store.js file that exports a data object for your application. This data object is shared with all of your components.
From the page linked above:
const sourceOfTruth = {}
const vmA = new Vue({
data: sourceOfTruth
})
const vmB = new Vue({
data: sourceOfTruth
})
and if you need components to have private state along with shared state:
var vmA = new Vue({
data: {
privateState: {},
sharedState: store.state
}
})
var vmB = new Vue({
data: {
privateState: {},
sharedState: store.state
}
})

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