I am iterating over a list on which I used a #click function to update some other elements. The elements indexes values are binded to selectedFixtures. I don't understand why, when I click on an element, it prints out [] and the second time I click on an element, it prints out the old value ex.: [1]. How can I work with the actual values in my function so it prints out [1] on the first time?
<v-chip-group
v-model="selectedFixtures"
multiple
>
<v-chip v-for="(f, i) in filteredFixtures()" :key="i" #click="selectFixture(f, i)">
<div class="d-flex align-baseline">
<span class="font-weight-medium">{{ f.name }}</span>
</div>
</v-chip>
</v-chip-group>
methods: {
selectFixture(f, index) {
console.log(JSON.stringify(this.selectedFixtures));
if (this.selectedFixtures.length === 1) {
console.log('here!')
}
}
}
You are wanting an array of chips chosen, so you are missing multiple from your template (is this just a typo when writing question?). As to your issue with old value, when the click event happens, selectedFixtures has yet to be updated with the value added/removed. You need to wait a tick to get the correct result:
Added multiple to template:
<v-chip-group v-model="selectedFixtures" multiple>
and adding waiting a tick in the function:
this.$nextTick(() => {
if (this.selectedFixtures.length === 1) {
console.log('here')
}
})
CODEPEN
PS, as a recommendation, don't call functions in template when not needing to, I'm talking about filteredFixtures(), you could instead use a computed property.
Related
I have two inputs that use the same function to set a new value like this
<b-input
v-model="ownerProps.approver2ExtraCost"
#blur="onClick($event)"
class="inputBuefy"
></b-input>
</div>
<b-input
class="inputBuefy"
#blur="onClick($event)"
v-model="ownerProps.approver3ExtraCost"
></b-input>
</div>
they have different v-models but I'm using the same function to change their values on my methods property.
onClick(e) {
console.log(e.target.value);
e.target.value = "dfg";
}
The thing is, when I change one of the following inputs it gets the previously value that I typed.
for example:
if typed 'ABC' in the first input
replaces it with 'dfg'
But when I go to the next input, and I type something like 'HIJ'
the first input get its previous value = 'ABC'
But it should have remained with 'dfg'
Your problem is that you are setting the value of the element and not changing the value of the bounded variable which you should do.
so when vue "refreshes" it updates the input
do this instead
<b-input
v-model="ownerProps.approver2ExtraCost"
#blur="onClick(2)"
class="inputBuefy"
></b-input>
</div>
<b-input
class="inputBuefy"
#blur="onClick(3)"
v-model="ownerProps.approver3ExtraCost"
></b-input>
</div>
and change your function to
onClick(id) {
if (id === 2) ownerProps.approver2ExtraCost = "dfg";
if (id === 3) ownerProps.approver3ExtraCost = "dfg";
}
you should ideally have those elements in a array instead and send the index of what you want to change
I'm writing a function to update a custom checkbox when clicked (and I don't want to use native checkbox for some reasons).
The code for checkbox is
<div class="tick-box" :class="{ tick: isTicked }" #click="() => isTicked = !isTicked"></div>
which works find.
However, there are so many checkboxes, so I use object to keep track for each item. It looks like this
<!-- (inside v-for) -->
<div class="tick-box" :class="{ tick: isTicked['lyr'+layer.lyr_id] }" #click="() => {
isTicked['lyr'+layer.lyr_id] = !isTicked['lyr'+layer.lyr_id]
}"></div>
Now nothing happens, no error at all.
When I want to see isTicked value with {{ isTicked }}, it's just shows {}.
This is what I define in the <script></script> part.
export default {
data() {
return {
isTicked: {},
...
};
},
...
}
Could you help me where I get it wrong?
Thanks!
Edit:
I know that declaring as isTicked: {}, the first few clicks won't do anything because its proerty is undefined. However, it should be defined by the first/second click not something like this.
Objects does not reflect the changes when updated like this.
You should use $set to set object properties in order to make them reactive.
Try as below
<div class="tick-box" :class="{ tick: isTicked['lyr'+layer.lyr_id] }" #click="onChecked"></div>
Add below method:
onChecked() {
this.$set(this.isTicked,'lyr'+this.layer.lyr_id, !this.isTicked['lyr'+this.layer.lyr_id])
}
VueJS watches data by reference so to update object in state you need create new one.
onChecked(lyr_id) {
const key = 'lyr'+lyr_id;
this.isTicked = {...this.isTicked, [key]: !this.isTicked[key]};
}
I'm using Vuetify and its v-select component with multiple option enabled to allow selecting multiple options.
These options represent talent(candidate) pools for my CRM software.
What it needs to do is that when some option in v-select is checked, candidates from checked talent pool are fetched from API and saved to some array (let's call it markedCandidates), and when option is deselected, candidates from that pool need to be removed from markedCandidates array.
The problem is that #change or #input events return complete list of selected options. I need it to return just selected/deselected pool and information if it's selected or deselected, to be able to update the markedCandidates array.
My existing code:
<v-select return-object multiple #change="loadCandidatesFromTalentPool" v-model="markedCandidates" :item-text="'name'" :item-value="'name'" :items="talentPoolsSortedByName" dense placeholder="No pool selected" label="Talent Pools" color='#009FFF'>
<template slot="selection" slot-scope="{ item, index }">
<span v-if="index === 0">{{ item.name }}</span>
<span v-if="index === 1" class="grey--text caption othersSpan">(+{{ talentPools.length - 1 }} others)</span>
</template>
</v-select>
Any idea how to solve this?
As I said, loadCandidatesFromTalentPool(change) returns complete array of v-model (markedCandidates)..
EDIT:
I found this solution, it's more of a workaround actually, would be nice if there was dedicated event for this situation:
https://codepen.io/johnjleider/pen/OByoOq?editors=1011
Actually there is only one event related to changing values of v-autocomplete : #change (See https://vuetifyjs.com/en/components/autocompletes#events). The watch approach is useful if you want to monitor only individual changes. However, if you plan to do this with more selectors, it could be better if you create a custom reusable component with a new attached event (in this example, for the last change).
Vue.component('customselector',{
props:[
"value",
"items"
],
data: function() {
return {
content: this.value,
oldVal : this.value
}
},
methods: {
handleInput (e) {
this.$emit('input', this.content)
},
changed (val) {
oldVal=this.oldVal
//detect differences
const diff = [
...val.filter(x => !oldVal.includes(x)),
...oldVal.filter(x => !val.includes(x))
]
this.oldVal = val
var deleted=[]
var inserted=[]
// detect inserted/deleted
for(var i=0;i<diff.length;i++){
if (val.indexOf(diff[i])){
deleted.push(diff[i])
}else{
inserted.push(diff[i])
}
}
this.$emit("change",val)
this.$emit("lastchange",diff,inserted,deleted);
}
},
extends: 'v-autocomplete',
template: '<v-autocomplete #input="handleInput" #change="changed" :items="items" box chips color="blue lighten-2" label="Select" item-text="name" item-value="name" multiple return-object><slot></slot></v-autocomplete>',
})
Then you can use your component as simple as:
<customselector #lastchange="lastChange" >...</customselector>
methods:{
lastChange: function(changed, inserted, deleted){
this.lastChanged = changed
}
}
The changed only shows items which are actually changed. I've added the inserted and deleted arrays to return new items added or removed from the selection.
Source example: https://codepen.io/fraigo/pen/qQRvve/?editors=1011
Replace
:item-text="'name'" :item-value="'name'"
by
item-text="name" item-value="name"
I'm using vue-select in my app and am trying to prevent an event handler from firing when the default values are first loaded into the vue-select input.
The component looks like this:
<v-select
multiple
v-model="product.recommended_accessories"
label="name"
:options="accessoryOptions"
#input="saveProduct"
#search="onAccessorySearch">
<template slot="option" slot-scope="option">
<h4>{{ option.name }}</h4>
<h5>{{ option.sku }}</h5>
</template>
</v-select>
As you can see, I want to save the product when the user changes the values in this multi-select. It works fine, but with one issue.
The value of the select is tied to the product.recommended_accessories data. Elsewhere in the app, a product is loaded from the server, which includes a recommended_accessories attribute. Loading the product then triggers saveProduct to be called since vue-select set the preselected options for the input, which apparently triggers the #input event.
Is there anyway around this? Maybe I have made some sort of design error here. Or maybe there is a hook I should be using to bind the event handler, or to set some sort of flag indicating that the product is in the process of being loaded and saving the product shouldn't occur.
I'm just trying to avoid saving the product immediately after it's loaded for no reason.
For now I am just tracking an accessoryEventCount variable that gets initialized to 0 whenever a product is loaded. Then I make sure accessoryEventCount > 0 before calling saveProduct on an v-select input event.
It works, but I am still wondering if there is a more elegant solution.
UPDATE
Looks like Vue.nextTick is what I was looking for. Before setting the value of product in code, I set a flag this.isSettingProduct = true. Then I set the product, and call Vue.nextTick(() => { this.isSettingProduct = false });.
Now I can avoid saving the product if this.isSettingProduct == true. Using Vue.nextTick ensures that the flag isn't set back to false until after the asynchronous data update completes.
It looks you should bind prop=onChange, though #input still seems working (check v-select github: line# 544).
Below is my solution, before loading your product, bind onChange with function () {}, after loaded, bind it with the function you like.
Vue.component('v-select', VueSelect.VueSelect)
app = new Vue({
el: "#app",
data: {
accessoryOptions: [
{'name':'a1', 'sku':'a2'},
{'name':'b1', 'sku':'b2'},
{'name':'c1', 'sku':'c2'}
],
product: {
recommended_accessories: []
},
saveProduct: function (){}
},
methods: {
onAccessorySearch: function () {
console.log('emit input')
},
loadProduct: function () {
this.product.recommended_accessories = ['a1', 'b1'] // simulate get data from the server
setTimeout( () => {
this.saveProduct = (value) => {
console.log('emit input', this.product.recommended_accessories)
}
}, 400)
}
}
})
#app {
width: 400px;
}
<script src="https://unpkg.com/vue#latest"></script>
<script src="https://unpkg.com/vue-select#latest"></script>
<div id="app">
<button #click="loadProduct()">Click Me!</button>
<v-select
multiple
v-model="product.recommended_accessories"
label="name"
:options="accessoryOptions"
:on-change="saveProduct"
#search="onAccessorySearch">
<template slot="option" slot-scope="option">
<span>{{ option.name }}</span>
<span>{{ option.sku }}</span>
</template>
</v-select>
</div>
I've got a CMS-like feature that has an article with multiple particles (called blocks). A particle can be a either a rich text field or a table. Based on the Block's discr attribute, a Quill or Handsontable instance should be initiated.
This works perfectly, until I reorder the blocks. When I've got a Quill instance and a Handsontable instance, after reordering them, the Quill gets a context menu from the Handsontable and the Quill instance gets a toolbar.
I'm new to Vue.js, but I already understand that happens. I've read List Rendering Caveats and Why isn’t the DOM updating?. The two div.chapterblock elements don't get reordered (like a jQuery-like application probably would do), but only their content changes. When I use the inspector, I see the .chapterblock#id and it's content changing, not moving. The (Quill/Handsontable/whatever) instance is bound to a specific DOM element and stays bound to the element, even if it changes.
But what I don't (yet) understand is how to solve the problem. How can I reorder items and keep the Quill/Handsontable instance on the right elements? Destroying and re-initializing the instances doesn't feel right.
My template:
<div class="chapterblock" v-for="(block, index) in blocks" v-bind:data-id="block.id">
<template v-if="block.discr == 'html'">
<div class="quill" v-html="block.content"></div>
</template>
<template v-if="block.discr == 'table'">
<script type="application/json" v-html="block.content"></script>
<div v-bind:id="'handsontable_' + block.id" class="handsontable-wrapper"></div>
</template>
<button v-if="index !== 0" v-on:click="move(block, 'up')">up</button>
<button v-if="index !== 1" v-on:click="move(block, 'down')">down</button>
</div>
Vue instance:
return new Vue({
//...
computed: {
blocks: function () {
return this.chapter.blocks.sort(function compare (a, b) {
if (a.position < b.position) {
return -1
}
if (a.position > b.position) {
return 1
}
return 0
})
}
},
methods: {
move: function (block, direction) {
if (direction === 'up') {
block.position = block.position - 1
} else if (direction === 'down') {
block.position = block.position + 1
}
// fetch to save position
}
}
Use the key attribute on the v-for loop to reorder the elements, instead of replacing their contents:
From https://v2.vuejs.org/v2/guide/list.html#key:
To give Vue a hint so that it can track each node’s identity, and thus reuse and reorder existing elements, you need to provide a unique key attribute for each item. An ideal value for key would be the unique id of each item.