Get input values from child components in Vue - vue.js

I would like to retrieve all input values from my child components (client and advice, seen below), but not sure how to proceed.
client.vue
<template>
<div id="client">
<input type="text" v-model="client.name" />
<input type="text" v-model="client.code" />
</div>
</template>
<script>
export default {
data() {
return {
client: {
name: '',
code: '',
}
}
}
}
</script>
advice.vue
<template>
<div id="advice">
<input type="text" v-model="advice.foo" />
<input type="text" v-model="advice.bar" />
<div v-for="index in 2" :key="index">
<input type="text" v-model="advice.amount[index]" />
</div>
</div>
</template>
<script>
export default {
data() {
return {
advice: {
foo: '',
bar: '',
amount:[]
}
}
}
}
</script>
Each component has more fields than the above example.
My home page (parent) looks as simple as:
<template>
<form id="app" #submit="printForm">
<clientInfo />
<advice />
<input type="submit" value="Print" class="btn" />
</form>
</template>
<script>
import clientInfo from "#/components/clientInfo.vue";
import advice from "#/components/advice.vue";
export default {
components: {
clientInfo,
advice
},
methods: {
printForm() {}
}
}
</script>
My first idea was to $emit, but not sure how to do that efficiently with more than 20 fields without attaching a #emitMethod="parentEmitMethod" to every single field.
My second idea was to have a Vuex store (as seen below), but I don't know how to save all the states at once and not sure if I should.
new Vuex.Store({
state: {
client: {
name:'',
code:''
},
advice: {
foo:'',
bar:'',
amount:[]
}
}
})

You could use FormData to get the values of the form's <input>s or <textarea>s that have a name attribute (anonymous ones are ignored). This works even if the form has nested Vue components that contain <input>s.
export default {
methods: {
printForm(e) {
const form = e.target
const formData = new FormData(form) // get all named inputs in form
for (const [inputName, value] of formData) {
console.log({ inputName, value })
}
}
}
}
demo

You could use v-model with your custom components. Let's say you want to use them like this:
<advice v-model="adviceData"/>
For this, you would need to watch for value changes on your input elements inside your advice component and then emit an input event with the values. This will update the adviceData binded property. One generic way to do this could be including a watcher inside your advice component, like this:
export default {
data() {
return {
advice: {
foo: '',
bar: '',
amount:[]
}
}
},
watch: {
advice: {
handler: function(newValue, oldValue) {
this.$emit('input', newValue);
},
deep: true,
}
},
}
This way you will not have to add a handler for each input field. The deep option must be included if we need to detect changes on nested data in the advice object.

I think you can achieve what you want is when the user writes something using#change this will trigger a method when the input value is changed, you could use a button instead or anything you want, like this:
The child component
<input type="text" v-model="advice.amount[index]" #change="emitCurrStateToParent ()"/>
You gotta add #change="emitCurrStateToParent ()" in every input you have.
emitCurrStateToParent () {
this.$emit("emitCurrStateToParent", this.advice)
}
Then in you parent component
<child-component v-on:emitCurrStateToParent="reciveDataFromChild ($event)"></child-component>
reciveDataFromChild (recivedData) {
// Do something with the data
}
I would use a button instead of #change, like a "Save" button idk, the same goes for vuex, you can use the #change event
saveDataAdviceInStore () {
this.$store.commit("saveAdvice", this.advice)
}
Then in the store
mutations: {
saveAdvice (state, advice) {
state.advice = advice
}
}

Related

how to validate child form from parent component in Vue

I have a child component which includes form:
<el-form :model="abc" ref="ruleForm" :rules="rules">
<el-form-item prop="files">
<abc-card :title="getTranslation('abc.files')">
<file-selector v-model="abc.files" />
</abc-card>
</el-form-item>
</el-form>
And I want to add simple validations to this form:
rules: function () {
return {
files: [
{
type: 'object',
required: true,
trigger: 'change',
message: 'Field required',
},
],
};
},
But my click button is in the parent component:
<files v-model="editableAbc" ref="editableTab" />
<el-button type="primary" #click="submitForm()">Create</el-button>
methods: {
submitForm() {
this.$refs.form.validate((isValid) => {
if (!isValid) {
return;
}
////API CALLS////
});
},
}
So I am trying to achieve that when the button is clicked the navigation should be rendered. How can I do that?
As per your requirement, My suggestion would be to use a ref on child component to access its methods and then on submit click in parent component, trigger the child component method.
In parent component template :
<parent-component>
<child-component ref="childComponentRef" />
<button #click="submitFromParent">Submit</button>
</parent-component>
In parent component script :
methods: {
submitFromParent() {
this.$refs.childComponentRef.submitForm();
}
}
In child component script :
methods: {
submitForm() {
// Perform validations and do make API calls based on validation passed.
// If you want to pass success or failure in parent then you can do that by using $emit from here.
}
}
The "files" component is the form you're talking about?
If so, then ref should be placed exactly when calling the 'files' component, and not inside it. This will allow you to access the component in your parent element.
<files v-model="editableAbc" ref="ruleForm" />
There is a method with the props, which was mentioned in the comments above. I really don't like it, but I can tell you about it.
You need to set a value in the data of the parent component. Next you have to pass it as props to the child component. When you click the button, you must change the value of this key (for example +1). In the child component, you need to monitor the change in the props value via watch and call your validation function.
// Parent
<template>
<div class="test">
<ChildComponent />
</div>
</template>
<script>
export default {
data() {
return {
updateCount: 0,
};
},
methods: {
submitForm() {
// yout submit method
this.updateCount += 1;
},
},
};
</script>
// Child
<script>
export default {
props: {
updateCount: {
type: Number,
default: 0,
},
},
watch: {
updateCount: {
handler() {
this.validate();
},
},
},
methods: {
validate() {
// yout validation method
},
},
};
</script>
And one more solution. It is suitable if you cannot place the button in the child component, but you can pass it through the slot.
You need to pass the validate function in the child component through the prop inside the slot. In this case, in the parent component, you will be able to get this function through the v-slot and bind it to your button.
// Parent
<template>
<div class="test">
<ChildComponent>
<template #button="{ validate }">
<button #click="submitForm(validate)">My button</button>
</template>
</ChildComponent>
</div>
</template>
<script>
import ChildComponent from "./ChildComponent";
export default {
components: {
ChildComponent,
},
methods: {
submitForm(cb) {
const isValid = cb();
// your submit code
},
},
};
</script>
// Child
<template>
<div class="child-component">
<!-- your form -->
<slot name="button" :validate="validate" />
</div>
</template>
<script>
export default {
methods: {
validate() {
// yout validation method
console.log("validate");
},
},
};
</script>

Vue.js how to check if inputs from child components are filled so parent component can able/disable a button

Hi I'm new to vuejs and I'm struggling figuring it out how to make this work.
I have 3 different child components in a parent component, each one of the child components have multiple text and radio inputs. What I want to acomplish is to be able to disable a button on the parent component if there are empty inputs or not selected radio buttons.
Can someone explain to me how could I approach this? Thank you!.
You are looking for how to emit data, opposite to passing data down through a prop.
Here is a small example for an input field.
Child1.vue
<template>
<p>
Write something:
<input v-model="inputText" />
</p>
<p>{{ inputText }}</p>
</template>
<script>
export default {
data() {
return {
inputText: '',
};
},
emits: ['emitInput'],
watch: {
inputText() {
this.checkContent();
},
},
methods: {
checkContent() {
this.$emit('emitInput', this.inputText === '');
},
},
};
</script>
App.vue (parent):
<template>
<div id="app">
<button :disabled="disabledButton">Parent Button</button>
<Child1 #emitInput="parentMethod" />
</div>
</template>
<script>
import Child1 from './Child1.vue';
export default {
name: 'App',
components: {
Child1,
},
data() {
return {
disabledButton: true,
};
},
methods: {
parentMethod(payload) {
//Since you had a 2nd parameter on line 24 in Child1, you can access it.
//We were checking if input is empty or not, returning a boolean.
this.disabledButton = payload;
},
},
};
</script>

sending drop-down value to parent

I have this form on my parent:
<template>
<b-form #submit="onSubmit">
<CountryDropdown/>
</b-form>
</template>
<script>
import ...
export default {
form: {
country: ''
}
}
</script>
This is my Dropdown component using vue-select:
<template>
<v-select label="countryName" :options="countries" />
</template>
<script>
export default {
data() {
return {
countries: [
{ countryCode: 'EE', countryName: 'Estonia' },
{ countryCode: 'RU', countryName: 'Russia' }
]
}
}
}
</script>
I need to pass the countryCode value to its parent's form.country. I tried using $emit, but I cant seem to figure out how upon selection
it will set the parent value, and not upon submit.
EDIT:
The submitted solutions work great, I'll add my solution here:
I added an input event to my v-select:
<v-select #input="setSelected" ... />
in my script i define the selected and setSelected method :
data()
return
selected: ''
setSelected(value) {
this.selected = value.countryCode
this.$emit("selected", value.countryCode)
}
And in the parent:
<CountryDropdown v-on:selected="getCountry />
and parent script:
getCountry(country) {
this.form.country = country
}
You could use Vue's v-model mechanism to bind the output of vue-select to form.country in the container.
In CountryDropdown, implement v-model:
Add a prop named value 1️⃣, and bind it to vue-select.value 2️⃣
Emit input-event with the desired value. In this case, we want to emit countryCode as the value. 3️⃣
<template>
<v-select
:value="value" 2️⃣
#input="$emit('input', $event ? $event.countryCode : '')" 3️⃣
/>
</template>
<script>
export default {
props: ['value'], // 1️⃣
}
</script>
Now, the container of CountryDropdown could bind form.country to it, updating form.country to the selected country's countryCode upon selection:
<CountryDropdown v-model="form.country" />
demo
As you seem to know, $emit is what you need to use to send an event from a component to its' parent. To make that happen you need to add a few more things to your current code.
To get the options to list in your v-select you should use a computed function to isolate the names, like this:
computed: {
countryNames() {
return this.countries.map(c => c.countryName)
}
},
You will then need to list the names in your v-select like this:
<v-select label="countryName" :items="countryNames" #change="selectedCountry" />
You will see that #change is calling a method, this will be the method to emit your country code and it can do so like this:
methods: {
selectedCountry(e) {
let code = this.countries.find(cntry => cntry.countryName === e)
this.$emit('code', code.countryCode)
}
},
You will need a listener in your parent to hear the emit, so add something like this:
<CountryDropdown v-on:code="countryCodeFunction"/>
And then you just need a countryCodeFunction() in your methods that does something with the emitted code.

Vue + Vuex: format input data

Inspired from several example, I'm trying to write a custom component that formats it's value with a specific method.
Here's the component:
<template>
<input
type="text"
v-model="inputValue"
/>
</template>
<script type="text/javascript">
import {formatPhoneNumber} from '~/utils/string';
export default {
computed: {
inputValue: {
get() {
return formatPhoneNumber(this.value)
},
set(value) {
this.$emit('input', formatPhoneNumber(value))
}
}
},
}
</script>
I'm using Vuex, and I call the component this way in the parent component:
<PhoneInput :value="cellPhoneNumber" class="input" #input="addCellPhoneNumber" />
computed: {
cellPhoneNumber() {
return this.$store.state.identity.cellPhoneNumber;
},
},
methods: {
addCellPhoneNumber: function(phoneNumber) {
this.$store.commit('identity/addCellPhoneNumber', phoneNumber)
},
}
The set part works, it goes to the store, but the data comes back to the component, cellPhoneNumber is called, but not inputValue#get.
Since it might be related to the fact that I use #input/:value in the parent component, I tried to use it also on it's child component:
<template>
<input
#input="formatValue"
type="text"
:value="formattedValue"
/>
</template>
<script type="text/javascript">
import {formatPhoneNumber} from '~/utils/string';
export default {
computed: {
formattedValue: function(){
return formatPhoneNumber(this.value)
},
},
methods: {
formatValue(e) {
this.$emit('input', formatPhoneNumber(e.target.value))
}
}
}
</script>
Without success, the same thing happens.
Can someone tell me what's going wrong?
As #ohgodwhy mentioned in the comments:
You're missing a prop definition in the component that expects this.value, so it's not reactive.

Vue: Using input value in function

I am using Single File Components and I have a modal component that has an
input box but I can't get the value of the input in a function below using the v-modal name. It keeps coming back as 'name is not defined'. Am I using the v-model attribute incorrectly?
<template>
<input v-model="name" class="name"></input>
</template>
<script>
export default {
methods: {
applyName() {
let nameData = {{name}}
}
}
}
</script>
You're right, you're using the v-model property incorrectly.
First off you need to define a piece of state in your component, using data:
export default {
data: () => ({
name: '',
}),
methods: {
log() {
console.log(this.name);
}
}
}
You can then bind this piece of data in your component using v-model="name", just like you did. However, if you want to access this piece of state in your method, you should be using this.name in your applyName() method.
Your {{name}} syntax is used to get access to the data in your template, like so:
<template>
<span>
My name is: {{name}}!
</span>
</template>
You have to use this pointer to access the model:
<template>
<input v-model="inputName" class="name"></input>
</template>
<script>
export default {
data() {
return {
inputName: '',
}
},
methods: {
applyName() {
// Notice the use of this pointer
let nameData = { name: this.inputName };
}
}
}
</script>
Look at the doc https://v2.vuejs.org/v2/guide/forms.html#v-model-with-Components
In the template, you are referring by name to data, computed or methods. In this case, it refers to data. When the input changes the name then the data is updated.
It is possible to use in a function referring to this.
<template>
<input v-model="name" class="name"></input>
</template>
<script>
export default {
data() {
return { name: '' }
},
methods: {
applyName() {
let nameData = this.name
}
}
}
</script>