Setting a 'default' v-on event for a component within Vue - javascript

I have a set of 'text-input' custom components which house some boilerplate markup and an 'input' element.
One way of getting the value of the 'text-input' in to it's parent is to $emit an event when the value has changed.
I need to capture and handle the $emit with a v-on for every text-input component:
<text-input v-on:valueUpdated="storeInputValue" name='name'></text-input>
<text-input v-on:valueUpdated="storeInputValue" name='email'></text-input>
<text-input v-on:valueUpdated="storeInputValue" name='phone'></text-input>
I feel that this introduces too much repetition in the code, and I was wondering if there were a way to have the v-on listener on the component template itself:
<template v-on:valueUpdated="storeInputValue">
...
</template>
So that there is a 'default' v-on listener for this component, every time it is used.

You can use v-model on custom components.
html
<div id="app>
<text-input v-model="user.name" name="'name'"></text-input>
<text-input v-model="user.email" name="'email'"></text-input>
<text-input v-model="user.phone" name="'phone'"></text-input>
<h4>{{user}}</h4>
</div>
script
Vue.component('text-input', {
name: 'text-input',
template: `
<div>
<label>{{name}}</label>
<input type="text" :value="value" #input="storeInputValue($event.target.value)" />
</div>
`,
props: ['value', 'name'],
methods: {
storeInputValue(value){
this.$emit('input', value);
}
}
});
//parent component
new Vue({
el: '#app',
data: {
user: {
name: '',
email: '',
phone: ''
}
}
});
here is the example fiddle

Related

child component emit an custom event, but parent component's listener not triggered

I'm registered a child component in Vue, the child will emit an custom event, but the parent component's listener not triggered.
<template id="add-item-template">
<div class="input-group">
<input #keyup.enter="addItem" v-model="newItem" >
<span class="input-group-btn">
<button #click="addItem" type="button">Add!</button>
</span>
</div>
</template>
<div id="app" class="container">
<h2>{{ title }}</h2>
<add-item-component v-on:itemAdd="addAItem"></add-item-component>
</div>
Vue.component('add-item-component', {
template: '#add-item-template',
data: function () {
return {
newItem: ''
};
},
methods: {
addItem() {
this.$emit('itemAdd');
console.log("itemAdd In add-item-component");
}
}
});
new Vue({
el: '#app',
data: {
title: 'Welcome to Vue'
},
methods: {
addAItem: function () {
console.log("In #app, addAItem()!");
}
}
});
The "itemAdd In add-item-component" log show in console, but "In #app, addAItem()!" log not, the #app's method addAItem not invoked.
The problem is that custom events should not be named with camelCase. If you look at the error message in the console, it tells you:
Event "itemadd" is emitted in component but the handler is registered for "itemAdd"
The component is emitting a lowercase version even though you've used camelCase to name it. Renaming to all lowercase or kebab-case will fix it.
In the parent template:
<add-item-component #itemadd="addAItem">
Emitting from the child:
this.$emit('itemadd');
This is discussed a bit with Evan You (Vue creator) here

shared v-model value between child and parent

I have a component which shares v-model same as parent component. The code is like below:
Vue.component('greeting', {
template: '<input type="text" :name="name" v-on:input="updateSearch($event.target.value)"> ' ,
props: ['name'],
methods: {
updateSearch: function(value) {
this.$emit('input', value);
}
}
});
const app = new Vue({
el: '#app',
data: {
name: ''
}
});
<script src="https://unpkg.com/vue#2.6.9/dist/vue.js"></script>
<div id="app">
Child: <greeting v-model="name"></greeting>
<br><br><br>
Main: <input type="text" v-model="name" placeholder="" />
</div>
I want to update both input boxes if the user enters text in either of them. Any suggestions would be helpful.
If you pass in a reference like an object as prop, you can bind a property of that object on both your parent and child
Vue.component('greeting', {
template: '<input type="text" v-model="name.value" />' ,
props: ['name']
});
const app = new Vue({
el: '#app',
data: {
name: { value: '' }
}
});
<script src="https://unpkg.com/vue#2.6.9/dist/vue.js"></script>
<div id="app">
Child: <greeting v-bind:name="name"></greeting>
<br><br><br>
Main: <input type="text" v-model="name.value" placeholder="" />
</div>
Usually is a bad practice change props inside child component. In this case, you can create two different variables and update the other one when some of them changes it value (via events and props).
So, greeting component would $emit some event which you will catch inside main component and update main's name
On the other hand, main component would pass a prop to greeting which will be reactive considering changes inside main and will update variable name inside greeting's data.
If you get more cases like that, think about using vuex
I think, what you are looking for is .sync modifier for events in Vue.js 2.3.0+.
You can find a sample implementation of the same in my article here.

VueJS sending v-model property from child to parent

Let's say I have a Vue component like this one:
Vue.component('child-comp',{
props:['name', 'val'],
data: function(){
return {
picked: ''
}
},
template: '<div><input type="radio" :name="name" :value="val" v-model="picked"><slot></slot></div>'
});
And The Parent vue instance:
new Vue({
el: '#app',
data: {
message: 'Hello'
}
});
And in the HTML:
<div id="app">
<child-comp name="fruits" val="apple">Apple</child-comp>
<child-comp name="fruits" val="banana">Banana</child-comp>
<child-comp name="fruits" val="cherry">Cherry</child-comp>
<p>{{ picked }}</p> <!-- this throws an error -->
</div>
How can I pass the v-model property picked from the child component to the root instance. Only way I know of is $emitting an event from the child component and later capturing the passed data in root instance. But as you can see, to access a simple property, triggering an event is overkill. How can I access {{ picked }} within <p>{{ picked }}</p>
If your child-comp is an input component you could use two-way props. These work similar to v-model but you can use them with your custom components.
<custom-input
:value="something"
#input="value => { something = value }">
</custom-input>
You can find out more about this here and there. See this thread also. Good luck!
That's easy:
new Vue({
el: '#app',
data: {
message: 'Hello',
picked: 'apple'
}
});
And in child :
Vue.component('child-comp',{
props:['name'],
template: '<div><input type="radio" :name="name" v-model="picked"><slot></slot></div>'
});

Vue: v-model doesn't work with dynamic components

For example: <component v-model='foo' :is='boo' ...>.
foo's value stays the same during input.
I'm trying to solve the issue for quite a long time. I've checked lots of questions and threads but none of those helped me.
HTML doesn't work:
<component
:is="field.component"
:key="key"
:name="field.name"
v-for="(field, key) in integration_data"
v-model="field.value"
>
</component>
HTML works fine:
<input
:key="key"
:name="field.name"
v-for="(field, key) in integration_data"
v-model="field.value"
>
Vue controller:
export default {
init: function (init_data) {
return new Vue({
data: {
integration_data: [
{name: 'field_name0', component: 'input', value: ''},
{name: 'field_name0', component: 'input', value: ''},
]
},
});
}
}
You can't use input as a type of component and expect it to be a native input element. :is must name a component (which can contain an input, if you want).
Then you have to understand how v-model works on components:
So for a component to work with v-model, it should (these can be
configured in 2.2.0+):
accept a value prop
emit an input event with the new value
Putting that all together, you can use v-model with :is.
new Vue({
el: '#app',
data: {
integration_data: [{
name: 'one',
component: 'one',
value: 'ok'
}]
},
components: {
one: {
props: ['name', 'value'],
template: '<div>{{name}} and <input v-model="proxyValue"><slot></slot></div>',
computed: {
proxyValue: {
get() { return this.value; },
set(newValue) { this.$emit('input', newValue); }
}
}
}
}
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<div id="app">
<component
:is="field.component"
v-for="(field, key) in integration_data"
:key="key"
:name="field.name"
v-model="field.value"
>
<div>{{field.value}}</div>
</component>
</div>
v-model has nothing to do with what you're possibly trying to do. It looks like you are trying to insert components dynamically. That's exactly what :is does. Now, to pass data to the component, you should use props.
For example:
Your Vue instance:
const vm = new Vue({
el: '#app',
data: {
exampleValue: 'This value will be passed to the example component'
}
})
Register a component:
Vue.component('example-component', {
// declare the props
props: ['value'],
template: '<span>{{ value}}</span>'
})
Then use it like this:
<example-component :value="exampleValue"></example-component>
Or:
<component :is="'example-component'" :value="exampleValue"></component>

Vue binding overrides element attribute

I have a component that renders a HTML input:
<input
:placeholder="placeholder"
v-model="value"
type="text"
:disabled="disabled"
:readOnly="readOnly"
#focus="onFocus"
/>
Note that the type is not binded/reactive.
When I put this component inside another, and bind a object to it, the type gets overrided.
<my-input v-bind="{type: 'foobar'}"></my-input>
Is this a by design or a bug?
Example (check the input[type] in the HTML):
const Input = {
template: '<input type="text"/>'
// ^^^^ "text" gets overriden to "foobar"
}
new Vue({
el: '#demo',
components: {
'my-input': Input
}
});
<script src="http://vuejs.org/js/vue.min.js"></script>
<div id="demo">
<my-input v-bind="{type: 'foobar'}"></my-input>
</div>
I answered this in an issue, this is expected
https://github.com/vuejs/vue/issues/5846#issuecomment-307098682
You can, however, disregard attrs by adding them as props and ignore them
const Input = {
props: ['type'],
template: '<input type="text"/>'
// ^^^^ "text" won't get overriden
}
new Vue({
el: '#demo',
components: {
'my-input': Input
}
});
Other attributes like class get merged but type can only be overriden
VueJS adds the component attributes to the first child node of the component template.
Look this fiddle
http://jsfiddle.net/8hzhvrng/
The my-input has a inputroot child and then it gets the type="password"
The my-input2 has a div root child which gets the type="number"

Categories