Reputation: 1002
I created two components with Vue.js and Laravel (FormComponent and ListComponent). In the form I should enter a movie name and then when I click the input button I should see the new movie in the list of movies that is located in ListComponent... however I am unable to do that. I alert the new movie correctly but I cannot see the new movie in the list.
FormComponent:
<template>
<div class="container">
<form>
<div class="form-group">
<label for="movie">Movie:</label>
<input type="text" class="form-control" v-bind:placeholder="movie_default" v-model="movie_default" id="movie">
</div>
<input type="button" value="Submit" @click="add_movie()">
</form>
</div>
</template>
<script>
export default {
mounted() {
console.log('Form Component mounted.')
},
data() {
return {
movie_default: 'Rainman'
}
},
methods: {
add_movie () {
alert(this.movie_default);
}
}
}
</script>
ListComponent:
<template>
<div class="container">
<ol>
<li v-for="movie in movie_list" :key="movie">
{{ movie }}
</li>
</ol>
</div>
</template>
<script>
export default {
mounted() {
console.log('List Component mounted.')
},
data() {
return {
movie_list: [ 'Titanic', 'Profondo rosso']
}
}
}
</script>
Tables.blade.php
<div id="app">
<div class="row">
<div class="col-sm-6">
<form-component></form-component>
</div>
<div class="col-sm-6">
<list-component></list-component>
</div>
</div>
</div>
Upvotes: 1
Views: 1199
Reputation: 2856
You have some different ways to solve your problem. I would suggest you the easiest for the result I think you want to accomplish.
Create a third component my-form, that looks like this:
myForm.vue
<template>
<div class="row">
<div class="col-sm-6">
<form-component @new-movie="addNewMovie"></form-component>
</div>
<div class="col-sm-6">
<list-component :movies="movies_list"></list-component>
</div>
</div>
</template>
<script>
export default {
name: "myForm.vue",
data() {
return {
movies_list: [],
new_movie: ""
}
},
methods: {
addNewMovie(movie){
this.movies_list.push(movie)
}
}
}
</script>
then edit your FormComponent to emit the new value on click:
methods: {
add_movie () {
alert(this.movie_default);
this.$emit('new-movie',this.movie_default);
}
and your ListComponent to use props instead of the state to display the movie list:
export default {
props:['movies'],
data() {
return {
}
}
and update your v-for with to use the prop:
<li v-for="movie in movies" :key="movie">
Another way would be to use a centralized store (vuex) to share the state between components
Upvotes: 3