How Do I Use Data From Vue.js Child Component Within Parent Component?
@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><divclass='form-group'><label>Name:</label><inputtype='text'class='form-control'v-model='name'></div><divclass='form-group'><location-input:location="locationData"></location-input></div><buttonclass='btn btn-primary'>{{buttontext}}</button><pre>{{ locationData | json }}</pre></div></template><script>exportdefault {
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'exportdefault {
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 versionlibraries: '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 = newVue({
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
Solution 2:
I would recommend the data store approach which is in the VueJS documentation here: https://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 = newVue({
data: sourceOfTruth
})
const vmB = newVue({
data: sourceOfTruth
})
and if you need components to have private state along with shared state:
varvmA=newVue({data: {
privateState: {},
sharedState:store.state
}
})varvmB=newVue({data: {
privateState: {},
sharedState:store.state
}
})
Solution 3:
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.
Post a Comment for "How Do I Use Data From Vue.js Child Component Within Parent Component?"