Value of <Input in Vue component not getting value of method - vuejs2

I have a list of users. Click on a specific user the user edit form is populated but the only way I can get a value in the input is by putting the return in the
<input v-model="this.cl.data.USER_RLTNP_SCTY_ACCS_GRP.User_Name" ref=User_Name>
if I do
<input v-model="User_Name "v-bind:value="this.cl.data.USER_RLTNP_SCTY_ACCS_GRP.User_Name">
Nothing appears in the input.
If I use the v-model="this.cl.data....." the value of the user_name is in the input I'm not sure how the value is passed to my updateUser() function because normally I would use username = this.User_Name
Using apollo and Graphgl for the querying
<template>
<div>
<v-text-field label="User Name" ref="User_Name" v-model="User_Name" v-bind:value="this.cl.data.USER_RLTNP_SCTY_ACCS_GRP[0].User_Name" id="" placeholder="User Name"></v-text-field>
<v-btn v-on:click="editUser()">Edit</v-btn>
</div>
</template>
<script>
import gql from graphql-tag import { SCTY_ACCS_GRP, SCTY_ACCS_GRP_USER }
from './gqlqueries'
export default {
data: () => ({
users: [],
cl: '',
user_form: false,
user_name: ''
}),
methods: {
editForm: async function(userid){
this.cl = await this.$apollo.query({query : SCTY_ACCS_GRP_USER, variables: {id : userid}})
this.user_form = true
console.log(this.cl)
alert(this.cl.data.USER_RLTNP_SCTY_ACCS_GRP[0].User_Name)
},
editUser(){
this.user_name = this.User_Name
alert(this.user_name)
}
},
mounted: async function() {
this.users = await this.$apollo.query({ query: SCTY_ACCS_GRP })
// console.log(this.users.data.USER_RLTNP_SCTY_ACCS_GRP)
} }
</script>
I would assume the <input v-bind:value="this.cl.data...."> Would populate once The editForm() function is triggered. So how do I get the value of the User_Name when the editUser button is clicked

You could try list rendering.
A little example :
https://jsfiddle.net/L4xu9r5g/7/
var mapp = new Vue({
el: "#app",
data: {
currentuserinfo : undefined,
users: [
{ name: "John Doe", id : 12},
{ name: "Black Jack", id : 932},
{ name: "White Jack", id: 342}
],
userinfo:
[
{ userid: 12, favcolor: 'green', age : 23},
{ userid: 932, favcolor: 'red', age : 11},
{ userid: 342, favcolor: 'blue', age : 12}
]
},
methods:
{
selectuser : function(id)
{
//your query here
this.currentuserinfo = this.userinfo.filter(u => u.userid ==id)[0];
}
}
})
td, th
{
padding: 5px;
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<table>
<tbody>
<tr>
<th>Name</th>
<th>Select User</th>
</tr>
<tr v-for="user in users" :key="user.id">
<td>{{user.name}}</td>
<td><button #click="selectuser(user.id)">Select User</button></td>
</tr>
</tbody>
</table>
<div v-if="currentuserinfo === undefined">
Please select a user
</div>
<div v-if="currentuserinfo != undefined">
<span>Favourite color : {{currentuserinfo.favcolor}}</span><br/>
<span>Age : {{currentuserinfo.age}}</span><br/>
</div>
</div>

Related

Vue-MultiSelect Checkbox binding

The data properties of the multi-select component does not update on change. Check-boxes doesn't update on the front-end.
Expected Behavior: The check-boxes should get ticked, when clicked.
Link to code: https://jsfiddle.net/bzqd19nt/3/
<div id="app">
<multiselect
select-Label=""
selected-Label=""
deselect-Label=""
v-model="value"
:options="options"
:multiple="true"
track-by="library"
:custom-label="customLabel"
:close-on-select="false"
#select=onSelect($event)
#remove=onRemove($event)
>
<span class="checkbox-label" slot="option" slot-scope="scope" #click.self="select(scope.option)">
{{ scope.option.library }}
<input class="test" type="checkbox" v-model="scope.option.checked" #focus.prevent/>
</span>
</multiselect>
<pre>{{ value }}</pre>
</div>
new Vue({
components: {
Multiselect: window.VueMultiselect.default
},
data: {
value: [],
options: [
{ language: 'JavaScript', library: 'Vue.js', checked: false },
{ language: 'JavaScript', library: 'Vue-Multiselect', checked: false },
{ language: 'JavaScript', library: 'Vuelidate', checked: false }
]
},
methods: {
customLabel(option) {
return `${option.library} - ${option.language}`;
},
onSelect(option) {
console.log('Added');
option.checked = true;
console.log(`${option.library} Clicked!! ${option.checked}`);
},
onRemove(option) {
console.log('Removed');
option.checked = false;
console.log(`${option.library} Removed!! ${option.checked}`);
}
}
}).$mount('#app');
In your code you call onSelect and try to change the option argument of this function inside the function:
option.checked = true;
This affects only the local variable option (the function argument). And doesn't affect objects in options array in the data of the Vue instance, the objects bound with checkboxes. That's why nothing happens when you click on an option in the list.
To fix it find the appropriate element in options array and change it:
let index = this.options.findIndex(item => item.library==option.library);
this.options[index].checked = true;
Here is the code snippet with fix:
new Vue({
components: {
Multiselect: window.VueMultiselect.default
},
data: {
value: [],
options: [
{ language: 'JavaScript', library: 'Vue.js', checked: false },
{ language: 'JavaScript', library: 'Vue-Multiselect', checked: false },
{ language: 'JavaScript', library: 'Vuelidate', checked: false }
]
},
methods: {
customLabel (option) {
return `${option.library} - ${option.language}`
},
onSelect (option) {
console.log("Added");
let index = this.options.findIndex(item => item.library==option.library);
this.options[index].checked = true;
console.log(option.library + " Clicked!! " + option.checked);
},
onRemove (option) {
console.log("Removed");
let index = this.options.findIndex(item => item.library==option.library);
this.options[index].checked = false;
console.log(option.library + " Removed!! " + option.checked);
}
}
}).$mount('#app')
* {
font-family: 'Lato', 'Avenir', sans-serif;
}
.checkbox-label {
display: block;
}
.test {
position: absolute;
right: 1vw;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link href="https://unpkg.com/vue-multiselect#2.0.2/dist/vue-multiselect.min.css" rel="stylesheet"/>
<script src="https://unpkg.com/vue-multiselect#2.0.3/dist/vue-multiselect.min.js"></script>
<div id="app">
<multiselect
select-Label=""
selected-Label=""
deselect-Label=""
v-model="value"
:options="options"
:multiple="true"
track-by="library"
:custom-label="customLabel"
:close-on-select="false"
#select=onSelect($event)
#remove=onRemove($event)
>
<span class="checkbox-label" slot="option" slot-scope="scope" #click.self="select(scope.option)">
{{ scope.option.library }}
<input class="test" type="checkbox" v-model="scope.option.checked" #focus.prevent/>
</span>
</multiselect>
<pre>{{ value }}</pre>
</div>

:class not updating when clicked in vuejs v-for

I want to add a css class to a item in v-for when the td in clicked
<template>
<div>
<h1>Forces ()</h1>
<section v-if="errored">
<p>We're sorry, we're not able to retrieve this information at the moment, please try back later</p>
</section>
<section v-if="loading">
<p>loading...</p>
</section>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>#</th>
<th>ID</th>
<th
#click="orderByName = !orderByName">Forces</th>
</tr>
<th>Delete</th>
</thead>
<tbody>
<tr v-for="(force, index) in forces" #click="completeTask(force)" :class="{completed: force.done}" v-bind:key="index">
<td>
<router-link :to="{ name: 'ListForce', params: { name: force.id } }">Link</router-link>
</td>
<th>{{ force.done }}</th>
<th>{{ force.name }}</th>
<th><button v-on:click="removeElement(index)">remove</button></th>
</tr>
</tbody>
</table>
<div>
</div>
</div>
</template>
<script>
import {APIService} from '../APIService';
const apiService = new APIService();
const _ = require('lodash');
export default {
name: 'ListForces',
components: {
},
data() {
return {
question: '',
forces: [{
done: null,
id: null,
name: null
}],
errored: false,
loading: true,
orderByName: false,
};
},
methods: {
getForces(){
apiService.getForces().then((data, error) => {
this.forces = data;
this.forces.map(function(e){
e.done = false;
});
this.loading= false;
console.log(this.forces)
});
},
completeTask(force) {
force.done = ! force.done;
console.log(force.done);
},
removeElement: function (index) {
this.forces.splice(index, 1);
}
},
computed: {
/* forcesOrdered() {
return this.orderByName ? _.orderBy(this.forces, 'name', 'desc') : this.forces;
}*/
},
mounted() {
this.getForces();
},
}
</script>
<style>
.completed {
text-decoration: line-through;
}
</style>
I want a line to go through the items when clicked, but the dom doesn't update. If I go into the vue tab in chrome I can see the force.done changes for each item but only if I click out of the object and click back into it. I'm not to sure why the state isn't updating as it's done so when I have used an click and a css bind before.
I've tried to make minimal changes to get this working:
// import {APIService} from '../APIService';
// const apiService = new APIService();
// const _ = require('lodash');
const apiService = {
getForces () {
return Promise.resolve([
{ id: 1, name: 'Red' },
{ id: 2, name: 'Green' },
{ id: 3, name: 'Blue' }
])
}
}
new Vue({
el: '#app',
name: 'ListForces',
components: {
},
data() {
return {
question: '',
forces: [{
done: null,
id: null,
name: null
}],
errored: false,
loading: true,
orderByName: false,
};
},
methods: {
getForces(){
apiService.getForces().then((data, error) => {
for (const force of data) {
force.done = false;
}
this.forces = data;
this.loading= false;
console.log(this.forces)
});
},
completeTask(force) {
force.done = ! force.done;
console.log(force.done);
},
removeElement: function (index) {
this.forces.splice(index, 1);
}
},
mounted() {
this.getForces();
}
})
.completed {
text-decoration: line-through;
}
<script src="https://unpkg.com/vue#2.6.10/dist/vue.js"></script>
<div id="app">
<div>
<h1>Forces ()</h1>
<section v-if="errored">
<p>We're sorry, we're not able to retrieve this information at the moment, please try back later</p>
</section>
<section v-if="loading">
<p>loading...</p>
</section>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>#</th>
<th>ID</th>
<th
#click="orderByName = !orderByName">Forces</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr v-for="(force, index) in forces" #click="completeTask(force)" :class="{completed: force.done}" v-bind:key="index">
<th>{{ force.done }}</th>
<th>{{ force.name }}</th>
<th><button v-on:click="removeElement(index)">remove</button></th>
</tr>
</tbody>
</table>
<div>
</div>
</div>
</div>
The key problem was here:
this.forces = data;
this.forces.map(function(e){
e.done = false;
});
The problem here is that the property done is being added to the data after it has been made reactive. The reactivity observers get added as soon as the line this.forces = data runs. Adding done after that counts as adding a new property, which won't work.
It's also a misuse of map so I've switched it to a for/of loop instead.
for (const force of data) {
force.done = false;
}
this.forces = data; // <- data becomes reactive here, including 'done'
On an unrelated note I've tweaked the template to move the Delete header inside the top row.
Make sure force.done is set to false in data before initialization so it is reactive.
data() {
return {
force:{
done: false;
}
}
}
If force exists but has no done member set, you can use Vue.set instead of = to create a reactive value after initialization.
Vue.set(this.force, 'done', true);

VueJS set first radiobutton as checked if v-model is empty

How can i have checked radio button in v-for, if my v-model is empty?
The list of users may be different, so I can't set selectedUserId: 665. I tried to use :checked="index == 0" but it does not work with v-model.
var radioVue = new Vue({
el: "#test",
data: {
selectedUserId: null,
users: [{id: 665, name: 'John'}, {id: 1135, name: 'Edward'}, {id: 7546, name: 'David'}]
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="test">
<div v-for="(user, index) in users">
<input type="radio" :value="user.id" v-model="selectedUserId"> {{ user.name }}
</div>
<span>{{ selectedUserId}}</span>
</div>
You can use watch for that:
watch: {
selectedUserId: {
handler(newVal) {
if (newVal === null || newVal === undefined) {
this.selectedUserId = this.users[0].id
}
},
immediate: true
}
}
for this you can use get/set on computed variable with your v-model
the setter does a standard set while the getter return the wanted users id or if there is not the id of the first user (as in first entry of the array)
var radioVue = new Vue({
el: "#test",
data: {
selectedUserId: 7546,
users: [{id: 665, name: 'John'}, {id: 1135, name: 'Edward'}, {id: 7546, name: 'David'}]
},
computed: {
checkedUserId: {
get() {
// need to use == instead of === because v-model seems to set as string :/
return this.users.some(user => user.id == this.selectedUserId) ? this.users.filter(user => user.id == this.selectedUserId)[0].id : this.users[0].id
},
set(val) {
// doing a parseInt() here would allow you to use === in get
this.selectedUserId = val
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="test">
<div v-for="user in users">
<input type="radio" :value="user.id" name="name" v-model="checkedUserId"> {{ user.name }} - {{ user.id }}
</div>
<span>{{ selectedUserId}}</span>
<input type="text" v-model="selectedUserId">
</div>

v-if and v-else not working after data array change

Depending on the array 'r.meta.fields' a specific sort icon of each column needs to be shown. When the template is rendering, it is working correctly. But when the array change, the template isn't changing anymore.
<th v-for="field in r.meta.fields">
{{field.label}}
<a href="#" #click.prevent="sortField(field)">
<div class="fa fa-sort-up" v-if="field.sort_direction === 'desc'"></div>
<div class="fa fa-sort-down" v-else-if="field.sort_direction === 'asc'"></div>
<div class="fa fa-sort" v-else-if="field.sortable"></div>
</a>
What could be the problem?
You could create a mapping for the sort icons and handle the changes on click:
const vm = new Vue({
el: '#app',
data() {
const iconMap = {
sort: {
'asc': 'fa-sort-up',
'desc': 'fa-sort-down'
}
};
return {
r: {
meta: {
fields: [
{
label: 'field #1',
sortable: false,
sort_direction: 'asc',
icon: ''
},
{
label: 'field #2',
sortable: true,
sort_direction: 'desc',
icon: iconMap.sort['desc']// Initially sortable in descending order
}
]
}
},
iconMap
}
},
methods: {
sortField(field) {
let direction = (field.sort_direction === 'asc') ? 'desc' : 'asc';
let icon = this.iconMap.sort[direction] || '';
field.sort_direction = direction;
field.icon = icon;
}
}
})
Template or HTML
<div id="app">
<table>
<tr>
<th v-for="field in r.meta.fields" :key="field.label">
{{field.label}}
<a href="#"
:class="field.icon"
#click.prevent="sortField(field)"></a>
</th>
</tr>
</table>
</div>
if you are using something like
r.meta.fields = newValue
then this won't work.
you should use
Vue.set(r.meta.fields, indexOfItem, newValue)
document here: vue update array

Reload a Component

I have 3 components. They are dashboard.vue, datatable.vue and modalbody.vue. After login my application reach in dashboard.vue. Where I call datatable.vue to display a list with some props. I have a button in datatable.vue. If I click on that button a modal will open to add new record to add that list (datatable.vue) using modalbody.vue.
Now I need to reload that list (datatable.vue) after inserting new record through modal (modalbody.vue).
How can I do that ?
I am going to show you a simple example how to do it.Hope you will get the logic
Component which has the table:
<template>
<div>
<cmp :modal.sync="modal" #personAdded="addItemInTable"></cmp>
<button #click="addNewPerson">add person</button>
<table>
<tr v-for="row in tableRows">
<td>{{ row.name }}</td>
<td>{{ row.lastName }}</td>
</tr>
</table>
</div>
</template>
<script>
import childComponent from 'ChildComponent.vue'
export default {
components: {
"cmp": childComponent
},
data() {
return {
modal: false,
tableRows: [
{ name: "person1", lastName: "lperson1" },
{ name: "person2", lastName: "lperson2" },
{ name: "person3", lastName: "lperson3" },
{ name: "person4", lastName: "lperson4" },
]
}
},
methods: {
addNewPerson() {
this.modal = true //open the modal
},
addItemInTable(data) {
//saving the data passed from modal
this.tableRows.unshift(data)
this.modal = false
}
}
}
</script>
Modal Component:
<template>
<div id="modal" v-if="modal">
<input type="text" v-model="name">
<input type="text" v-model="">
<button #click="save">Save</button>
<button #click="cancel">Cancel</button>
</div>
</template>
<script>
export default {
props: {
modal: {
default: false
}
},
data() {
return {
name: '',
lastName: ''
}
},
methods: {
save() {
const savedData = {
name: this.name,
lastName: this.lastName
}
this.$emit('personAdded', savedData)
},
cancel() {
this.$emit('update:modal', false)
}
}
}
</script>
<style>
.modal {
position: absolute;
height: 500px;
width: 500px;
display: flex;
justify-content: center;
align-items: center;
z-index: 999;
}
</style>
I dont have run the above code but the logic is correct.Please read below to understand:
For .sync modifier read this
For emitting events ($emit) read this
For reusing components read this