I have an array with many checkbox.
<li v-for='item in resultQuery' :key='item.id'>
<label class='custom-checkbox'>
<input type='checkbox' :value='item.id' v-model='checkBrands'>
<span #click='loadProducts(item.seoName)>{{ item.title }}</span>
</label>
</li>
I need to get true or false (depends on checkbox). How can I do this without affecting the v-model? (Use it to transfer an array of selected checkbox).
Needed to trigger a specific mutation
.then((response) => {
if(true) {
this.$store.commit(
'showFilteredList',
response.data.items
);
} else {
this.$store.commit(
'deleteCheckboxItems',
response.data.items
);
}
});
You can using #change on checkbox.
Example: https://codepen.io/koei5113/pen/ZEXLLgL
<input type='checkbox' :value='item.id' v-model='checkBrands' #change="changeEvent">
methods: {
...,
changeEvent($event) {
console.log($event.target.checked);
}
}
In this example you can see your v-model still working and you still can check checkbox status by the change event.
v-model ignore the :value in the input. You need to use :checked and #change
For example, and when you emit the change event use your function.
<input type="checkbox" :checked="value" #change="changeArrayNotValue" />
Related
I have these lines inside my component:
<li
v-for="(c, i) in choice[messagesRobot[numMessage].choice]"
:key="`choice-${choice[messagesRobot[numMessage].choice]}-${i}`">
<input
#change="changeValue($event, messagesRobot[numMessage].choice)"
:value="c.id"
type="checkbox"
:name="choix[messagesRobot[numMessage].choice]"
:id="`c-${choix[messagesRobot[numMessage].choice]}-${i}`">
<label :for="`c-${choix[messagesRobot[numMessage].choice]}-${i}`">
{{ c.nom }}
</label>
</li>
As you can see, there are a lot of computed properties. What I would like is to update the model when the user changes the value. The problem is that I can't use something like :v-model="xxx", so I have to capture the #change event. I wrote this:
function changeValue(e, v) {
console.log(v);
console.log(JSON.stringify(e.target.value));
}
The second line only gives me the last element the user selected or unselected, what I would like is to get ALL the values of the checkboxes, in an array, as it would do if I could use a v-model.
Thanks in advance for your help :)
I think you could do something like this
<li
v-for="(c, i) in choice[messagesRobot[numMessage].choice]"
:key="`choice-${choice[messagesRobot[numMessage].choice]}-${i}`">
<input
#change="changeValue($event, messagesRobot[numMessage].choice, i)"
:value="c.id"
type="checkbox"
:name="choix[messagesRobot[numMessage].choice]"
:id="`c-${choix[messagesRobot[numMessage].choice]}-${i}`">
<label :for="`c-${choix[messagesRobot[numMessage].choice]}-${i}`">
{{ c.nom }}
</label>
</li>
data() {
return {
valuesArray: []
}
}
function changeValue(e, v, index) {
this.valuesArray[index] = e.target.value;
console.log(v);
console.log(JSON.stringify(e.target.value));
}
then your valuesArray would have all the checked values.
Why can't you just use v-model?
Is it possible to pass v-model value to another component ? I have HTML code is like below
<div id='example-3'>
<input type="checkbox" id="jack" value="Jack" v-model="checkedNames">
<label for="jack">Jack</label>
<input type="checkbox" id="john" value="John" v-model="checkedNames">
<label for="john">John</label>
<input type="checkbox" id="mike" value="Mike" v-model="checkedNames">
<label for="mike">Mike</label>
</div>
vue.js code is like below
data: {
checkedNames: []
}
I can use this v-model value in same component using below code.
<span>Checked names: {{ checkedNames }}</span>
But how can I use v-model value in another component ?
You can emit events with the v-model value each time one of the checkboxes is ticked:
<input type="checkbox" id="mike" value="Mike" v-model="checkedNames" #change="onChange">
<label for="mike">Mike</label>
methods: {
onChange () {
this.$root.$emit('checkbox.changed', this.checkedNames)
}
}
Listen for the event in another component:
// my-component.js
created () {
this.$root.$on('checkbox-changed', payload => {
// do something with payload...
}
}
In the context of components, you should always be declaring the data property as a function, too.
data () {
return {}
}
Your other option is using a state management strategy, i.e.
Vuex, or similar.
On created I:
created: function () {
_.forEach(this.users, (user) => {
Vue.set(user, 'published', true);
});
}
In my template I have:
<div v-for="user in this.users">
<input type="checkbox" v-model="user.published">
</div>
The issue is the checkbox does not seem to be bound to the newly set published property. Why is this and how can I fix it?
Please note, I am unable to change how I am adding the published property to each user.
Try it that way:
<div v-for="user in users">
<input type="checkbox" v-model="user.published">
<button #click="user.published=!user.published">Toggle</button>
</div>
In your hook:
created() {
for (i in this.users) {
this.users[i].published = true;
}
}
I'm having trouble binding radiobuttons to boolean values in model.
In this example: https://jsfiddle.net/krillko/npv1snzv/2/
On load, the radio radio button is not checked, and when I try to change them, the 'primary' value in model is becomes empty.
I've tried:
:checked="variation.primary == true"
but with no effect.
To bind radio buttons to boolean values instead of string values in Vue, use v-bind on the value attribute:
<input type="radio" v-model="my-model" v-bind:value="true">
<input type="radio" v-model="my-model" v-bind:value="false">
I'll leave it to you to figure out how to match these values with your backend data.
Checkboxes are not so good for this scenario; the user could leave them both blank, and you don't get your answer. If you are asking a yes/no or true/false question where you want only one answer, then you should be using radio buttons instead of checkboxes.
What you are looking for is a checkbox. Here is an updated jsfiddle.
Your use case is not how radio buttons are supposed to work.
Look at this example.
new Vue({
el: '#app',
data: {
picked: 'One',
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.1/vue.js"></script>
<div id="app">
<input type="radio" id="one" value="One" v-model="picked">
<label for="one">One</label>
<br>
<input type="radio" id="two" value="Two" v-model="picked">
<label for="two">Two</label>
<br><br>
<span>Picked: {{ picked }}</span>
</div>
I ran into this myself too, the thing to remember is that the value attribute actually shouldn't change for the radio button, what changes (and what you need to bind to) is the checked attribute.
And then you need to handle the change event to set the correct item's value in your data.
Based on your jsFiddle, I think this is what you're looking for:
<div id="l-main">
<div v-for="(variation, key) in variations">
<label>
{{ variation.name }}
<input
type="radio"
name="Test"
:value="key"
:checked="variation.primary"
#change="onChange"
/>
</label>
</div>
<br>Output:<br>
<div v-for="(variation, key) in variations">
{{ variation.name }} {{ variation.primary }}
</div>
</div>
var vm = new Vue({
el: '#l-main',
data: {
variations: {
'41783' : {
'name': 'test1',
'primary': false
},
'41785' : {
'name': 'test2',
'primary': true
}
}
},
methods: {
onChange($event) {
// the primary variation is the one whose key
// matches the value of the radio button that got checked
for (const key in this.variations) {
this.variations[key].primary = key === $event.target.value;
}
}
}
});
I am trying to make a radio button checked using vuejs v-for only if my if-statement is true. Is there a way to use vuejs' v-if/v-else for this type of problem?
in php and html I can achieve this by doing the following:
<input type="radio" <? if(portal.id == currentPortalId) ? 'checked="checked"' : ''?>>
Below is what I have so far using vuejs:
<div v-for="portal in portals">
<input type="radio" id="{{portal.id}}" name="portalSelect"
v-bind:value="{id: portal.id, name: portal.name}"
v-model="newPortalSelect"
v-on:change="showSellers"
v-if="{{portal.id == currentPortalId}}"
checked="checked">
<label for="{{portal.id}}">{{portal.name}}</label>
</div>
I know the v-if statement here is for checking whether to show or hide the input.
Any help would be very much appreciated.
You could bind the checked attribute like this:
<div v-for="portal in portals">
<input type="radio"
id="{{portal.id}}"
name="portalSelect"
v-bind:value="{id: portal.id, name: portal.name}"
v-model="newPortalSelect"
v-on:change="showSellers"
:checked="portal.id == currentPortalId">
<label for="{{portal.id}}">{{portal.name}}</label>
</div>
Simple example: https://jsfiddle.net/b4k6tpj9/
Maybe someone finds this approach helpful:
In template I assign each radio button a value:
<input type="radio" value="1" v-model.number="someProperty">
<input type="radio" value="2" v-model.number="someProperty">
Then in the component I set the value, i.e:
data: function () {
return {
someProperty: 2
}
}
And in this case vue will select the second radio button.
You can follow below option if you can adjust with your logic:
<div class="combination-quantity">
<input type="radio" value="Lost"
v-model="missing_status">
<label for="lost">Lost</label>
<br>
<input type="radio" value="Return Supplier" v-model="missing_status">
<label for="return_supplier">Return Supplier</label>
</div>
Value for missing_status could be "Lost" or "Return Supplier" and based on the value radio option will be get selected automatically.
Below is an example of keeping track of the selected radiobutton, by
applying a value binding to the object (:value="portal") and
applying a v-model binding to the currently selected object (v-model="currentPortal").
The radiobutton will be checked automatically by Vue, when the two match (no :checked binding necessary!).
Vue 3 with composition API
Vue.createApp({
setup() {
const portals = [{
id: 1,
name: "Portal 1"
}, {
id: 2,
name: "Portal 2"
}];
const currentPortal = portals[1];
return {
portals,
currentPortal
}
}
}).mount("#app");
<script src="https://unpkg.com/vue#next"></script>
<div id="app">
<template v-for="portal in portals">
<input
type="radio"
:id="portal.id"
name="portalSelect"
:value="portal"
v-model="currentPortal">
<label :for="portal.id">{{portal.name}}</label>
</template>
</div>
I would like to point out a few options when dealing with radios and vue.js. In general if you need to dynamically bind an attribute value you can use the shorthand binding syntax to bind to and calculate that value. You can bind to data, a computed value or a method and a combination of all three.
new Vue({
el: '#demo',
data() {
return {
checkedData: false,
checkedGroupVModel: "radioVModel3", //some defaul
toggleChecked: false,
recalculateComputed: null
};
},
computed: {
amIChecked() {
let isEven = false;
if (this.recalculateComputed) {
let timeMills = new Date().getMilliseconds();
isEven = timeMills % 2 === 0;
}
return isEven;
}
},
methods: {
onToggle() {
this.toggleChecked = !this.toggleChecked;
return this.toggleChecked;
},
mutateComputedDependentData() {
this.recalculateComputed = {};
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="demo">
<div>
<div>
<span>Simple Radio Group - Only one checked at a time. Bound to data.checkedData</span><br>
<label>Radio 1 - inverse of checkedData = {{!checkedData}}
<input type="radio" name="group1" value="radio1" :checked="!checkedData">
</label><br>
<label>Radio 2 - checkedData = {{checkedData}}
<input type="radio" name="group1" value="radio2" :checked="checkedData">
</label><br>
<span>Understanding checked attribute: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-checked</span>
</div>
<br>
<div>
<span>Simple Radio - Checked bouned to semi-random computed object</span><br>
<label>Radio 1: {{amIChecked}}
<input type="radio" :checked="amIChecked">
</label>
<label>Recalculate Computed Value
<button type="button" #click="mutateComputedDependentData">Click Me Several Times</button>
</label>
</div>
<br>
<div>
<span>Simple Radio Group - v-model bound value = {{checkedGroupVModel}}</span><br>
<label>Simple Radio 1:
<input type="radio" name="vModelGroup" value="radioVModel1" v-model="checkedGroupVModel">
</label><br>
<label>Simple Radio 2:
<input type="radio" name="vModelGroup" value="radioVModel2" v-model="checkedGroupVModel">
</label><br>
<label>Simple Radio 3:
<input type="radio" name="vModelGroup" value="radioVModel3" v-model="checkedGroupVModel">
</label>
</div>
<br>
<div>
<span>Simpe Radio - click handler to toggle data bound to :checked to toggle selection</span><br>
<label>Toggle Radio = {{toggleChecked}}
<input type="radio" :checked="toggleChecked" #click='onToggle()'>
</label>
</div>
</div>
</div>