I'm trying to implement handsontable. As per my requirement, I want to re-render handsontable from changing a dropdown value, but on dropdown selection, the handsontable does not update properly. Below is my code:
Handsontable.vue:
<template>
<div id="hot-preview">
<HotTable :settings="settings" :ref="referenceId"></HotTable>
<div></div>
</div>
</template>
<script>
import { HotTable } from '#handsontable-pro/vue';
export default {
components: {
HotTable
},
props: ['settings', 'referenceId'],
}
</script>
<style>
#hot-preview {
max-width: 1050px;
height: 400px;
overflow: hidden;
}
</style>
Parent component:
<template>
<div id="provisioning-app">
<v-container grid-list-xl fluid>
<v-select
:items="selectList"
item-text="elementName"
item-value="elementName"
label="Standard"
v-model="selected"></v-select>
<handsontable :settings.sync="settings" :referenceId="referenceId"></handsontable>
</v-container>
</div>
</template>
<script>
import Handsontable from '#/components/Handsontable';
import PrevisioningService from '#/services/api/PrevisioningService';
export default {
components: {
Handsontable
},
data: () => ({
selectList: [],
selectApp: [],
selectedOption: '',
referenceId: 'provision-table',
}),
created(){
PrevisioningService.getProvisioningList(this.$session.get('userId'), this.$session.get('customerId')).then(response => {
this.provisioningList = response;
});
},
beforeUpdate() {
this.provisioningApp = this.getProvisioningAppList;
},
computed: {
settings () {
return {
data: this.getSelectApp,
colHeaders: ["Data Uploaded on", "Duration in Minutes", "Start Time", "Shift","Description","Next Day Spill Over", "Site Name"],
columns: [
{type: 'text'},
{type: 'text'},
{type: 'text'},
{type: 'text'},
{type: 'text'},
{type: 'text'},
{type: 'text'}
],
rowHeaders: true,
dropdownMenu: true,
filters: true,
rowHeaders: true,
search: true,
columnSorting: true,
manualRowMove: true,
manualColumnMove: true,
contextMenu: true,
afterChange: function (change, source) {
alert("after change");
},
beforeUpdate: function (change, source) {
alert("before update");
}
}
},
getSelectApp () {
if(this.selectedOption !== undefined && this.selectedOption !== null && this.selectedOption !== ''){
PrevisioningService.getProvisioningAppList(this.selectedOption, this.$session.get('userId'), this.$session.get('customerId')).then(response => {
this.provisioningApp = response;
return this.provisioningApp;
});
}
}
},
method: {
getSelected () {
return this.selectedOption;
}
}
};
</script>
With the above code, my data is received successfully from the server, but I'm unable to update the data in handsontable, as shown in the following screenshots:
How do I properly render the table after the dropdown selection?
I see two issues:
handsontable appears to not handle dynamic settings (see console errors), so settings should not be a computed property. Since the only settings property that needs to be updated is settings.data, that property alone should be mutated (i.e., don't reset the value of settings).
To address this, move settings into data(), initializing settings.data to null so that it would still be reactive:
data() {
settings: {
data: null,
colHeaders: [...],
...
}
},
computed: {
// settings() { } // DELETE THIS
}
getSelectApp is a computed property that is incorrectly asynchronous (i.e., in this case, it fetches data and handles the response later). A computed property cannot be asynchronous, so this computed property actually returns undefined. While there is a return call inside the computed property, the return does not set the value of the computed property because it's inside a Promise callback:
PrevisioningService.getProvisioningAppList(/*...*/).then(response => {
this.provisioningApp = response;
return this.provisioningApp; // DOES NOT SET COMPUTED PROPERTY VALUE
});
Also note the side effect from this.provisioningApp = response. It doesn't seem this.provisionApp is needed in this code in any case, so it should be removed as clean-up.
It seems the intention of this computed property is to update settings.data based on the value of the selected option. To accomplish that, you would have to use a watcher on selectedOption, which would change settings.data.
watch: {
selectedOption(val) {
PrevisioningService.getProvisioningAppList(/*...*/).then(response => {
this.settings.data = response;
});
}
},
demo
Related
I am using buefy taginput in my form, everything works as expect filter using ontype event.
only problem here is that i can see data in taginput box on when i focus, its getting selected too, but when i type its not getting filtered. for 10-15 items its not a problem but when its 1000+ items, it will be difficult. i don't know whats the problem here.
here is code so far.
<template>
<b-field label="Popular Destinations">
<b-taginput
v-model="form.popularSubDests"
:data="allSubDests"
autocomplete
:allow-new="allowNew"
:open-on-focus="openOnFocus"
field="SubDestName"
icon="label"
placeholder="Add Cities"
#typing="getFilteredSubdest"
>
</b-taginput>
</b-field>
</template>
<script>
export default {
data() {
return {
openOnFocus: false,
isSelectOnly: false,
allowNew: false,
allSubDestinations: [],
form: {
popularSubDests: [
{
SubDestName: null,
SubDestId: null,
},
],
},
}
},
computed: {
allSubDests() {
return this.allSubDestinations.map((item) => ({
SubDestId: item.id,
SubDestName: item.subdestname,
}))
},
},
methods: {
getFilteredSubdest(text) {
this.allSubDests = this.allSubDests.filter((option) => {
return option.SubDestName.toString().toLowerCase().indexOf(text.toLowerCase()) >= 0
})
},
},
async asyncdata({ route }) {
let { data: allSubDest } = await axios.get(`process.env.FETCHSUBDEST`)
return {
allSubDestinations: allSubDest.results,
}
},
}
</script>
I have a form component with a check box that needs to be true/false. The form is bound to a vuex store.
I set the initial value to true and it is checked on load. But when I uncheck it the value changes to "on" and i can not re-check it.
<div class="form-group form-check">
<input type="checkbox" name="product_inventory_item" class="form-check-input" #change="updateWorkingProductDataField('product_inventory_item', $event.target.value)" v-model="workingProductData.product_inventory_item"/>
<label class="form-check-label">Inventory Item?</label>
</div>
My Vuex Store:
export const state = {
workingProductData: {
product_inventory_item: true,
//This value is changed to "on" when the checkbox is clicked
//The check box will no longer check after it is unchecked
//How do i set the value to true/false based on checked or unchecked?
}
};
export const getters = {
workingProductData: state => {
return state.workingProductData;
}
};
export const mutations = {
updateWorkingProductDataProperty(state, payload){
state.workingProductData[payload.field] = payload.value;
},
};
export const actions = {
updateWorkingProductData({commit, state}, payload){
commit('updateWorkingProductDataProperty', payload);
},
};
My Component Object:
export default {
name: "ProductForm",
props: {
editing: {
type: Boolean,
required: false,
default: false,
},
categoryID: {
type: Number,
required: false,
default: null
}
},
data(){
return {
}
},
emits: ['updateProductData', 'addNewProductData'],
methods:{
updateWorkingProductDataField(field, value) {
this.$store.dispatch('product/updateWorkingProductData', {field: field, value: value});
},
submitProductForm(){
},
clearFormData(){
}
},
computed:{
workingProductData: function() {
return this.$store.getters['product/workingProductData'];
},
productCategories(){
return this.$store.getters['productCategory/productCategories'];
}
}
}
Thanks for any help!!
$event.target.value is giving on, instead you need to use $event.target.checked, which gives true or false. So change the template to:
#change="updateWorkingProductDataField('product_inventory_item', $event.target.checked)"
I have an array of objects, each has a URL that is being loaded in this file:
<template>
<div>
<img :key="id" :src="img" alt="" class="image box" #click="cardClicked" />
</div>
</template>
<script lang="ts">
export default {
props: ["id", "value", "type", "owner", "imgURL"],
data() {
return {
img: require(`./../assets/${this.imgURL}.png`)
};
},
methods: {
cardClicked() {
this.$store.commit("addCardToPlayer", {
id: this.id,
type: this.type,
value: this.value,
owner: this.owner
});
}
}
};
</script>
In the Store mutation I preform filtering and while filtering I add the card to a another player, like so:
addCardToPlayer(state, clickedCard) {
const owner = clickedCard.owner;
const type = clickedCard.type;
const currPlayer = state.currentPlayerName;
if (clickedCard.owner === "deck") {
state.cardOwners[owner].cards[type] = state.cardOwners[owner].cards[
type
].filter(card => {
if (card.id === clickedCard.id) {
state.cardOwners[currPlayer].cards[type].push(card);
return false;
} else return true;
});
}
},
When clicking a card to remove, I see the card being added to the player and displayed correctly, and the number of cards displayed after removal is correct.
But
The card that was removed still shows.
What have I tried:
Forcing to re-render using:
cardClicked() {
this.$store.commit("addCardToPlayer", {
id: this.id,
type: this.type,
value: this.value,
owner: this.owner
});
this.$forceUpdate();
}
Making different components have key, and trying to change the key to cause a re-render:
data() {
return {
componentKey: 0,
};
},
methods: {
forceRerender() {
this.componentKey += 1;
}
}
Tried changing how I change the array by creating a new state.
EDIT: Tried using computed. i get an error:
TypeError: Cannot read property 'imgURL' of undefined
computed: {
getImg: () => {
return require(`./../assets/${this.imgURL}.png`);
}}
EDIT: I wrote the computed function as arrow function, which doesn't preserve context.
SOLVED, by using
computed: {
getImg() {
return require(`./../assets/${this.imgURL}.png`);
}}
How can I make the images update after click (remove).
Thanks.
SOLVED, by using
computed: {
getImg() {
return require(`./../assets/${this.imgURL}.png`);
}}
I used the vue 2. I had a data from ajax, this is my code example:
<template>
<div>
<input type="input" class="form-control" v-model="siteInfo.siteId">
<input type="input" class="form-control" v-model="siteInfo.info.name">
<input type="input" class="form-control" v-model="siteInfo.accountData.name">
</div>
</template>
<script>
export default {
name: 'Site',
data() {
return {
siteInfo: {},
/* siteInfoName: '', */
}
},
/*computed: {
siteInfoName: function() {
return siteInfo.info.name || '';
},
...
},*/
methods: {
getData() {
// do ajax get data
this.$http.post('URL', {POSTDATA}).then(response => {
/*
response example
{ body:
data: {
sitdeId: 1,
info: { name: 'test'},
accountData: { name: 'accountTest'},
}
}
*/
this.siteInfo = response.body.data;
})
}
},
mounted() {
this.getData();
}
}
</script>
I got a warring message
[Vue warn]: Error in render: "TypeError: Cannot read property 'name'
of undefined"
I can use computed to fix it, but if I had a lot model, I should
write a lot computed.
I should create a lot data for those model?
I should not use an object to bind a lot model?
Does it have another solution for this situation? Thanks your help.
Before the data loads siteInfo.info will be undefined, so you can't access name in the v-model:
v-model="siteInfo.info.name"
Likewise for siteInfo.accountData.name.
My suggestion would be to set the initial value of siteInfo to null and then put a v-if="siteInfo" on the main div. Alternatively you could put a v-if on the individual input elements that checks for siteInfo.info and siteInfo.accountData.
You may also want to consider showing alternative content, such as a load mask, while the data is loading.
Don't be worried about too many v-models - you can do an iteration on the Object - like with Object.entries().
Vue.component('list-input-element', {
props: ['siteLabel', 'siteInfo'],
template: '<div><label>{{siteLabel}}<input type="input" class="form-control" v-model="siteInfo"></label></div>'
})
new Vue({
name: 'Site',
el: '#app',
data() {
return {
siteInfo: {},
}
},
methods: {
getData() {
// using mockup data for this example
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => {
console.log(json)
this.siteInfo = json
})
// do ajax get data
/*this.$http.post('URL', {
POSTDATA
}).then(response => {
this.siteInfo = response.body.data;
})*/
}
},
mounted() {
this.getData();
}
})
div {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<list-input-element v-for="siteInfo in Object.entries(siteInfo)" :site-label="siteInfo[0]" :site-info="siteInfo[1]" />
</div>
Rounding up
So, when you do the single file template, use a computed value, and return an Object from that.
Base your v-for on that computed, and you'll have no problems.
Something like this:
<template>
<div>
<input type="input" class="form-control" v-for="infoEl in siteInfoComputed" v-model="infoEl">
</div>
</template>
<script>
export default {
name: 'Site',
data() {
return {
siteInfo: {},
}
},
computed: {
siteInfoComputed: function() {
// you could check for all the keys-values you want here, and handle
// 'undefined' problem here
// so, actually you "create" the Object here that you're going to use
let ret = {}
// checking if this.siteInfo exists
if (Object.keys(this.siteInfo).length) ret = this.siteInfo
return ret
},
},
methods: {
getData() {
// do ajax get data
this.$http.post('URL', {POSTDATA}).then(response => {
/*
response example
{ body:
data: {
sitdeId: 1,
info: { name: 'test'},
accountData: { name: 'accountTest'},
}
}
*/
this.siteInfo = response.body.data;
})
}
},
mounted() {
this.getData();
}
}
</script>
I'm trying to set up a Vue component that takes a flat list of items in an array, groups them by a property for use in a sub-component, and emits the updated flat array.
My section component uses these grouped items in their v-model and emits the updated list. The section component is a drag-and-drop with some input fields, so items are changed under the section component and the updated list is emitted.
Here's an example of the component that takes the flat list as a prop:
<template>
<div>
<div v-for="section in template.sections" :key="section.id">
<h2>{{ section.name }}</h2>
<item-section :section="section" v-model="sectionData[section.id]"></item-section>
</div>
</div>
</template>
<script type="text/javascript">
import { groupBy } from "lodash";
import ItemSection from "#/components/Section.vue";
export default {
name: "ItemAssignment",
props: {
// All items in flat array
value: {
type: Array,
required: true,
default: () => [
/**
* {
* id: null,
* section_id: null,
* name: null
* }
*/
]
},
// Template (containing available sections)
template: {
type: Object,
default: () => {
return {
sections: [
/**
* {
* id: null,
* name: null
* }
*/
]
};
}
}
},
components: {
ItemSection
},
data() {
return {
sectionData: []
};
},
mounted() {},
computed: {
flattenedData() {
return Object.values(this.sectionData).flat();
}
},
methods: {},
watch: {
// Flat list updated
value: {
immediate: true,
deep: true,
handler(val) {
this.sectionData = groupBy(val, "section_id");
}
},
// --- Causing infinite loop ---
// flattenedData(val) {
// this.$emit("input", val);
// },
}
};
</script>
The parent of this component is basically this:
<template>
<div>
<!-- List items should be updatable here or from within the assignment component -->
<item-assignment v-model="listItems"></item-assignment>
</div>
</template>
<script type="text/javascript">
import ItemAssignment from "#/components/ItemAssignment.vue";
export default {
name: "ItemExample",
props: {
},
components: {
ItemAssignment
},
data() {
return {
listItems: []
};
},
mounted() {},
computed: {
},
methods: {
// Coming from API...
importExisting(list) {
var newList = [];
list.forEach(item => {
const newItem = {
id: null, // New record, so don't inherit ID
section_id: item.section_id,
name: item.name
};
newList.push(newItem);
});
this.listItems = newList;
}
},
watch: {
}
};
</script>
When emitting the finalized flat array, Vue goes into an infinite loop trying to re-process the list and the browser tab freezes up.
I believe the groupBy and/or Object.values(array).flat() method are stripping the reactivity out so Vue constantly thinks it's different data, thus the infinite loop.
I've tried manually looping through the items and pushing them to a temporary array, but have had the same issue.
If anyone knows a way to group and flatten these items while maintaining reactivity, I'd greatly appreciate it. Thanks!
So it makes sense why this is happening...
The groupBy function creates a new array, and since you're watching the array, the input event is triggered which causes the parent to update and pass the same value which gets triggered again in a loop.
Since you're already using lodash, you may be able to include the isEqual function that can compare the arrays
import { groupBy, isEqual } from "lodash";
import ItemSection from "#/components/Section.vue";
export default {
// ...redacted code...
watch: {
// Flat list updated
value: {
immediate: true,
deep: true,
handler(val, oldVal) {
if (!isEqual(val, oldVal))
this.sectionData = groupBy(val, "section_id");
}
},
flattenedData(val) {
this.$emit("input", val);
},
}
};
this should prevent the this.sectionData from updating if the old and new values are the same.
this could also be done in flattenedData, but would require another value to store the previous state.