Answer the question
In order to leave comments, you need to log in
How to bind form component in Vue js?
I have a form component, I need to pass the value from the inputs to the App component
From the input and texarea, I need to take the values and pass them to the App in data
I did it using $emit, but are there any more correct
Form.vue solutions
<template>
<div>
<slot></slot>
<form @submit.prevent>
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" v-model="title" />
</div>
<div class="form-group">
<label for="text">Text</label>
<textarea class="form-control" id="text" v-model="text"></textarea>
</div>
<button type="submit" class="btn btn-primary" @click="addToDo">Submit</button>
</form>
</div>
</template>
<script>
export default {
name: "Form",
data() {
return {
title: "",
text: "",
};
},
methods: {
addToDo() {
const newToDo = {
title: this.title,
text: this.text,
id: Math.random(),
};
this.text ='';
this.title = '';
this.$emit('addToDoItem',newToDo)
},
},
};
</script>
<template>
<div class="container pt-5">
<form-component
@addToDoItem="addToDo($event)"
>
<h1>ToDo list app</h1>
</form-component>
<hr />
<ul class="list-group">
<to-do-item
v-for="item in todoArr" :key="item.id"
:title='item.title'
:text='item.text'
:id="item.id"
:delite='delite'
>
</to-do-item>
</ul>
</div>
</template>
<script>
import ToDoItem from './components/ToDoItem';
import FormComponent from './components/Form'
export default {
name: 'App',
data() {
return {
title:'',
text:'',
todoArr:[
{
title:'Hello 1111',
text:'Lorem ipsum dolor sit.',
id:Math.random()*100
},
{
title:'Hello 2222',
text:'Lorem ipsum dolor sit.',
id:Math.random()*100
},
]
}
},
components: {
ToDoItem,
FormComponent,
},
methods:{
delite(id){
this.todoArr = [...this.todoArr].filter(item=>item.id !== id)
},
addToDo(obj){
// const newToDo = {
// title:this.title,
// text:this.text,
// id:Math.random()
// }
// this.text =''
// this.title = ''
this.todoArr = [...this.todoArr,obj]
}
}
}
</script>
Answer the question
In order to leave comments, you need to log in
I would replace two properties with one object , pass it as a v-model to the component.
In a component something like this:newItem: {title:'', text:''}
...
props:['value'],
data(){return {local: null}},
watch: {
value: {handler(newVal) {this.local=newVal}, deep: true, immediate: true},
local: {handler(newVal) {this.$emit('input', newVal)}, deep: true}
}
...
In this case, $emit will do. If the project becomes more complicated, then you will need to switch to vuex (for example, if you need to pass data through several components, and not immediately to the parent).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question