Passing data from parent component to a child component - javascript

I have a parent component as follows
<template>
<div class="row">
<mappings mapping-list="{{currentMappings}}"></mappings>
</div>
</template>
<script>
import Mappings from './content/Mappings.vue';
export default {
data () {
return {
currentMappings: Array
}
},
created () {
this.readData();
},
methods: {
readData () {
this.$http.get('data/Books.xml').then((response)=> {
var x2js = new X2JS();
var jsonObj = x2js.xml_str2json( response.body );
this.getMappings(jsonObj.WAStatus);
});
},
getMappings (jsonObj) {
this.currentMappings = jsonObj.WSSMappings;
}
},
components: { Mappings }
};
</script>
and a child "mappings" component as follows
<template>
<div class="col-lg-4">
<div class="hpanel stats">
<div class="panel-body h-200">
<div class="stats-title pull-left">
<h3>Mappings</h3>
</div>
<div class="stats-icon pull-right">
<img src="images/mappings.png" class="browserLogo">
</div>
<div class="m-t-xl">
<table class="table table-striped table-hover">
<tr v-for="mapping in mappingList ">
<td>name - {{$index}}</td>
</tr>
</table>
</div>
</div>
<div class="panel-footer">
Current WSS - SA Mappings
</div>
</div>
</div>
</template>
<script>
export default {
props: {
mappingList:Array
},
created () {
console.log(this.mappingList);
// console.log(this.$parent.mappings);
}
}
</script>
I am unable to pass data from the parent component to the child component. I am trying to use props here. The error that I am getting is
main.js:2756[Vue warn]: Invalid prop: type check failed for prop "mappingList". Expected Array, got String. (found in component: <mappings>)
Update
As per the suggestions made I have updated the parent component as follows
<template>
<div class="row">
<browser-stats></browser-stats>
</div>
<div class="row">
<mappings :mapping-list="currentMappings"></mappings>
</div>
</template>
<script>
import Mappings from './content/Mappings.vue';
export default {
data () {
return {
currentMappings: []
}
},
created () {
this.readData();
},
methods: {
readData () {
this.$http.get('data/WA_Status.xml').then((response)=> {
var x2js = new X2JS();
var jsonObj = x2js.xml_str2json( response.body );
this.getMappings(jsonObj.WAStatus);
});
},
getMappings (jsonObj) {
this.currentMappings = jsonObj.WSSMappings;
console.log(this.currentMappings.length);
console.log(JSON.stringify(this.currentMappings));
}
},
components: { Mappings }
};
</script>
and the child "mappings" component as follows
<template>
<div class="col-lg-4">
<div class="hpanel stats">
<div class="panel-body h-200">
<div class="stats-title pull-left">
<h3>Mappings</h3>
</div>
<div class="stats-icon pull-right">
<img src="images/mappings.png" class="browserLogo">
</div>
<div class="m-t-xl">
<table class="table table-striped table-hover">
<tr v-for="mapping in mappingList ">
<td>{{mapping._name}}</td>
</tr>
</table>
</div>
</div>
<div class="panel-footer">
Current WSS - SA Mappings
</div>
</div>
</div>
</template>
<script>
export default {
props: {
mappingList:[]
}
}
</script>
but I am getting an empty mappingList which means whenever I am doing console.log(this.currentMappings.length); I get undefined..
Can you please let me know what I am doing wrong here ?
Thanks

1) Fist issue
data () {
return {
currentMappings: Array
}
Should be
data () {
return {
currentMappings: []
}
2) Second issue
<mappings mapping-list="{{currentMappings}}"></mappings>
Should be:
<mappings :mapping-list="currentMappings"></mappings>
3) Third issue
created () {
console.log(this.mappingList);
// console.log(this.$parent.mappings);
}
This will return empty array every time. Because mappingList changed via AJAX and it's happed after created() was called. Try to use vue-devtool (chrome plugin) for better debug experience.
UPDATED:
To be able to watch async changes (like made with AJAX) consider to use watch this way:
{
data(){
//..
},
watch:{
'currentMappings'(val){
console.log('currentMappings updated', currentMappings);
}
}
}
Docs are here.

You use string interpolation ({{ }}) to try and pass the data to the prop - but the interpolation will turn the array into a string.
You should use a binding with v-bind
<mappings v-bind:mapping-list="currentMappings"></mappings>
...short form:
<mappings :mapping-list="currentMappings"></mappings>

Related

Vuejs SearchBar ||using filter method not working

I quite new to Vue js I am trying to use the computed method to create a search bar to only search through the name but I'm getting "this.info.filter" is not a function
<template>
<div class="container">
<input type="text" v-model="search" placeholder="Search by name">
<div class="content" v-for="student in filterName " v-bind:key="student.id">
<img class="image" :src="student.pic" alt="">
<div class="student-info">
<h1 class="info">{{student.firstName +" "+ student.lastName}}</h1>
<div class="infomation">
<p class="cop">{{ student.company }}</p>
<p class="ski">{{ student.skill }}</p>
<p class="email">{{ student.email }}</p>
<p class="grade">{{ student.grades }}</p>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from "axios";
export default {
name: "Student.vue",
data() {
return {
students: '',
search: ''
}
},
mounted() {
axios
.get('https://api.hatchways.io/assessment/students')
.then((res) => {
this.students = (res.data.students)
})
},
computed :{
filterName:function (){
return this.info.filter((student)=>{
return student.company.matcth(this.search);
})
}
}
}
</script>
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
First time using StackOverflow too please ignore the errors
I don't see a declaration/initialization for this.info anywhere in your code.
The reason you're getting that error is because filter is trying to run on an undefined variable (this.info is undefined).
You might want to initialize that to an empty array within data.

exception "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException"

Using Vue(SPA) in Laravel-8
I am trying to use event and fetch some data from the component but the data is not being fetched and the error that I am getting is:- 404
exception "Symfony\Component\HttpKernel\Exception\NotFoundHttpException"
Here's the Contacts.vue that I am using to send DisplayMessages event request:-
<template>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Contacts List</div>
<div class="card-body">
<ul v-for="contact in contacts" :key="contact.id" >
<li>
<button #click="displayMesages(contact.id)">
{{contact.name}}
</button>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data(){
return {
contacts: []
}
},
mounted() {
axios.get('/api/contacts-list')
.then(response => this.contacts = response.data)
},
methods: {
displayMesages(id){
console.log(id);
DisplayMessages.$emit('refresh', id);
}
}
}
</script>
Here's the DisplayMessages.vue where the request is being receieved:-
<template>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Display Messages</div>
<div class="card-body">
<h2 v-for="message in messages">{{message.message}}</h2>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
// import contacts from './ContactsList.vue';
export default {
data() {
return {
contacts: [],
messages: []
}
},
mounted() {
DisplayMessages.$on('refresh', (id)=>{
axios.get('/api/display-message/'+ id).then(response => this.messages = response.data)
});
}
}
</script>
Here's the route DisplayMessages is fetching:-
Route::get('/api/display-messages/{id}', [App\Http\Controllers\ChatsController::class, 'displayMessages']);
Here's the Controller:-
public function displayMessages($id)
{
return Chats::all();
}
There is a typing mistake in DisplayMessages.vue in axios route:-
mounted() {
DisplayMessages.$on('refresh', (id)=>{
axios.get('/api/display-message/'+ id).then(response => this.messages = response.data) //It should be '/api/display-messages/`
});
}
Does this route actually exist and return something?
/api/contacts-list

Vue - Emitting a data object but changing one changes them all

I have a TODO app and want to pass by props from one component to another an array of objects. An object is added every time you click a button but I'm having trouble with it. The problem is that the property value becomes the same for every single object added to the array. It seems like it's not saving correctly each tareas.tarea data.
App.vue
<template>
<div>
<Header></Header>
<AgregarTarea #tareaAgregada="agregarTarea"></AgregarTarea>
<div class="container">
<div class="columns">
<div class="column">
<Lista :tareas = 'tareas' #eliminarItem="eliminarTarea"></Lista>
<!-- here i pass through props the array of objects -->
</div>
<div class="column">
<TareaFinalizada></TareaFinalizada>
{}
</div>
</div>
</div>
</div>
</template>
<script>
import Header from './components/Header'
import AgregarTarea from './components/AgregarTarea'
import Lista from './components/Lista'
import TareaFinalizada from './components/TareaFinalizada'
export default {
data(){
return {
tareas:[]
}
},
components: {
Header,
AgregarTarea,
Lista,
TareaFinalizada
},
methods: {
agregarTarea(data){
//add new object to the array
this.tareas.push(data)
},
eliminarTarea(data) {
this.tareas.splice(data.id, 1);
}
}
};
</script>
AgregarTarea.vue || Here is where i add a new ToDo
<template>
<div class="container">
<input class="input" type="text" placeholder="Text input" v-model="tareas.tarea">
<button class="button is-primary" #click="agregarTarea">Agregar Tarea</button>
</div>
</template>
<script>
export default {
data(){
return {
tareas: {
tarea:'',
id:null,
editar:false
}
}
},
methods: {
agregarTarea(){
this.$emit('tareaAgregada', this.tareas)
this.tareas.tarea = ' ';
}
}
}
</script>
Lista.vue || And here is where i display the ToDo's
<template>
<div>
<div class="list is-hoverable">
<ul>
<li v-for="(tarea, index) in tareas" :key="index">
<a class="list-item has-text-centered" #click="editarTexto(index)">
{{ tarea }}
<div class="editar" v-if="editar">
<input class="input" type="text" placeholder="Text input" v-model="nuevaTarea">
</div>
</a>
<button class="button is-danger" #click="eliminarItem(index)">Eliminar</button>
<div><input type="checkbox"> Finalizada</div>
</li>
</ul>
</div>
</div>
</template>
<script>
export default {
props:['tareas'],
data(){
return {
nuevaTarea: ' ',
editar:false,
}
},
methods: {
eliminarItem(index){
this.$emit('eliminarItem', index)
},
editarTexto(){
this.editar = true
}
}
}
</script>
<style scoped>
</style>
JavaScript objects are passed by reference (not cloned by value). Each time you $emit the tareas object from AgregarTarea.vue, it's the same object reference as before, even if the properties have changed. So all of the objects in your tareas array in App.vue are the same object.
To fix this, change AgregarTarea.vue to $emit a clone each time:
methods: {
agregarTarea(){
this.$emit('tareaAgregada', Object.assign({}, this.tareas)) // clone
this.tareas.tarea = ' ';
}
}
(This is a shallow clone and would not work properly if this.tareas had nested objects, but it doesn't.)
Option #2
Here's a different way that works easily for nested objects:
new Vue({
el: "#app",
data(){
return {
tareas: null // <-- It's not filled here
}
},
methods: {
resetTareas() { // <-- it's filled here instead
this.tareas = {
tarea:'',
id:null,
editar:false
}
},
agregarTarea(){
this.$emit('tareaAgregada', this.tareas);
this.resetTareas(); // <-- Create a brand new object after emitting
}
},
created() {
this.resetTareas(); // <-- This is for the first one
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
Tarea: <input type="text" v-model="tareas.tarea" /><br /><br />
<button #click="agregarTarea">Emit</button><br /><br />
Object: {{ tareas }}
</div>
Since resetTareas creates a brand new object every time, you don't have to worry about cloning anything, and it works even if tareas is a complex nested object.

Bind element inside a for loop Vue not working properly

In the following Vue Component I want to loop through dwarfs array. And as long as I am in the current component, everything is fine (TEST) and also all the following properties are correct.
Currenct_Component.vue :
<template>
<div>
<h2>Stamm: {{ tribeName }}</h2>
<div class="card-container">
<div class="card" style="width: 18rem;" v-for="dwarf in dwarfs" :key="dwarf.name">
<!-- TEST -->
<p>{{dwarf}}</p>
<!-- CHILD COMPONENT -->
<app-modal
:showModal="showModal"
:targetDwarf="dwarf"
#close="showModal = false"
#weaponAdded="notifyApp"
/>
<!-- <img class="card-img-top" src="" alt="Card image cap">-->
<div class="card-body">
<h3 class="card-title" ref="dwarfName">{{ dwarf.name }}</h3>
<hr>
<ul class="dwarf-details">
<li><strong>Alter:</strong> {{ dwarf.age }}</li>
<li><strong>Waffen:</strong>
<ul v-for="weapon in dwarf.weapons">
<li><span>Name: {{ weapon.name }} | Magischer Wert: {{ weapon.magicValue }}</span></li>
</ul>
</li>
<li><strong>Powerfactor:</strong> {{ dwarf.weapons.map(weapon => weapon.magicValue).reduce((accumulator, currentValue) => accumulator + currentValue) }}</li>
</ul>
<button class="card-button" #click="showModal = true"><span class="plus-sign">+</span> Waffe</button>
</div>
</div>
</div>
<button id="backBtn" #click="onClick">Zurück</button>
</div>
</template>
<script>
import Modal from './NewWeaponModal.vue';
export default {
data() {
return {
showModal: false,
}
},
components: { appModal : Modal },
props: ['tribeName', 'dwarfs'],
methods: {
onClick() {
this.$emit('backBtn')
},
notifyApp() {
this.showModal = false;
this.$emit('weaponAdded');
}
},
}
</script>
But when I bind the element dwarf to the Child Component <app-modal/> it changes to the next dwarf in the array dwarfs (TEST) - (So as the result when i add a new weapon in the modal-form it gets added to the second dwarf...):
Child_Component.vue :
<template>
<div>
<div class="myModal" v-show="showModal">
<div class="modal-content">
<span #click="$emit('close')" class="close">×</span>
<h3>Neue Waffe</h3>
<!-- TEST -->
<p>{{ targetDwarf }}</p>
<form>
<input
type="text"
placeholder="Name..."
v-model="weaponName"
required
/>
<input
type="number"
placeholder="Magischer Wert..."
v-model="magicValue"
required
/>
<button #click.prevent="onClick">bestätigen</button>
</form>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
weaponName: '',
magicValue: '',
}
},
props: ['showModal', 'targetDwarf'],
methods: {
onClick() {
if(this.weaponName !== '' &&
Number.isInteger(+this.magicValue)) {
let newData = {...this.dwarf};
newData['weapons'] = [
...this.dwarf['weapons'],
{
"name": this.weaponName,
"magicValue": Number.parseInt(this.magicValue)
},
];
this.$http.post("https://localhost:5019/api", newData)
.then(data => data.text())
.then(text => console.log(text))
.catch(err => console.log(err));
this.$emit('weaponAdded');
} else {
alert('You should fill all fields validly')
}
},
}
}
</script>
It looks like you have the <app-modal/> component inside of the v-for="dwarf in dwarfs" loop, but then the control for showing all of the modal components created by that loop is just in one variable: showModal. So when showModal is true, the modal will show each of the dwarfs, and I'm guessing the second dwarf's modal is just covering up the first one's.
To fix this, you could move the <app-modal /> outside of that v-for loop, so there's only one instance on the page, then as part of the logic that shows the modal, populate the props of the modal with the correct dwarf's info.
Something like this:
<div class="card-container">
<div class="card" v-for="dwarf in dwarfs" :key="dwarf.name">
<p>{{dwarf}}</p>
<div class="card-body">
<button
class="card-button"
#click="() => setModalDwarf(dwarf)"
>
Waffe
</button>
</div>
</div>
<!-- Move outside of v-for loop -->
<app-modal
:showModal="!!modalDwarfId"
:targetDwarf="modalDwarfId"
#close="modalDwarfId = null"
#weaponAdded="onDwarfWeaponAdd"
/>
</div>
export default {
//....
data: () => ({
modalDwarfId: null,
)},
methods: {
setModalDwarf(dwarf) {
this.modalDwarfId = drawf.id;
},
onDwarfWeaponAdd() {
//...
}
},
}
You could then grab the correct dwarf data within the modal, from the ID passed as a prop, or pass in more granular data to the modal so it's more "dumb", which is the better practice so that the component isn't dependent on a specific data structure. Hope that helps
Courtesy of #Joe Dalton's answer, a bit alternated for my case:
<div class="card" style="width: 18rem;" v-for="dwarf in dwarfs" :key="dwarf.name">
...
<button class="card-button" #click="setModalDwarf(dwarf)"><span class="plus-sign">+</span> Waffe</button>
<div>
<app-modal
:showModal="showModal"
:targetDwarf="currentDwarf"
#close="showModal = false"
#weaponAdded="notifyApp"
/>
<script>
import Modal from './NewWeaponModal.vue';
export default {
data() {
return {
showModal: false,
currentDwarf: null,
}
},
components: { appModal : Modal },
props: ['tribeName', 'dwarfs'],
methods: {
setModalDwarf(dwarf) {
this.currentDwarf = dwarf;
this.showModal = true;
},
...
}
</script>

Passing an array to a component in Vue.js 2.0

I am passing an array to a component in Vue.js but it is not passing properly. Strings pass fine. My code is below:
Vue code
<template>
<div class="panel panel-default">
<div class="panel-heading">{{c}}</div>
<div class="panel-body">
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
mounted() {
console.log('Component ready.');
},
props: ['f','c'],
data : function() {
return {
}
},
And the HTML/PHP
<div class="container">
<div class="row">
<div class="col-md-12">
<?php $a = ['Pasta', 'Chicken', 'Rice']; ?>
<credits f= $a c="One"></credits>
</div>
</div>
</div>
In this case "c" works fine and "f" doesn't.
How can I do this properly?
Maybe try to encode the value using json_encode()like this:
<credits f="<?= json_encode($a)?>" c="One"></credits>

Categories

Resources