I'm trying to call a Vuex getter in the component watch.
But it tells me that it is undefined what is not.
So i try to return the getter in the computed object but still doesn t work.
name: "FreeTalk",
computed: {
...mapGetters(['getCharacter','getResultStatus', 'getFreeTalkText', 'getResult', 'freeTalkResult', 'getFreeTalkNoNative', 'getFreeTalkMedium','getFreeTalkNative']),
progressStatus() {
return this.getResult.progress
},
getStatus() {
return this.getResultStatus
}
},
watch: {
progressStatus: (val) => {
if (val == 100) {
this.status = this.getStatus()
if (this.getStatus === 0) {
this.outputText = this.getFreeTalkNoNative.result;
} else if (this.getStatus === 1) {
this.outputText = this.getFreeTalkMedium;
} else if (this.getStatus === 2) {
this.outputText = this.getFreeTalkNative;
}
}
}
},
data() {
return {
outputText: '',
ready: false,
isRecordDone: false,
status: -1
}
}
}
Related
I have 1 component to which I pass a computed as a prop in this way:
<Datatable :extraParams="extraParams" />
the computed is in the attached image.
I'm having trouble with the value of this property: coverageSelected:coverageData
Coverage data is filled by a select multiple
The problem I have is that when selecting an element of the select, first the component function is executed, then the coverageSelected property is empty, then the computed is executed and until this moment the coverageSelected array is filled, then until the second attempt It already has a full array.
This is my computed
props: [
"status_selected",
"rows",
"totals",
"dateRangeValue",
"coverageSelected",
"coverageList",
"showAll",
"dateFilterSelected",
],
computed(){
extraParams() {
let coverageData = this.coverageList.filter((m) => this.coverageSelected.includes(m.variable));
return {
status: this.status_selected,
dateRange: this.dateRangeValue,
dateFilterSelected: this.dateFilterSelected,
coverageSelected: coverageData, //This is the property that is not late.
showAll: this.showAll,
};
},
}
Another detail to mention that this.coverageSelected is a prop
The method that is executed first in the computed is this:
async getList(params) {
this.loading = true;
try {
if (params) {
this.query = { ...this.query, ...params, ...this.extraParams, filters: this.filters };
} else {
this.query = { ...this.query, ...this.extraParams, filters: this.filters };
}
const { data } = await this.$axios.post(`${this.$config.routePrefix}${this.action}`, this.query);
if (data.code == 200) {
this.rows = data.rows;
this.total = data.total;
this.$emit("listed", data);
}
} finally {
this.loading = false;
}
},
I have following store defined:
state: () => ({
infoPackCreationData: null,
infoPackCreationTab: null,
}),
getters: {
infoPackImage(state: any) {
return state.infoPackCreationTab && state.infoPackCreationTab.infopackContents
? state.infoPackCreationTab.infopackContents.filter((item: any) => item.type === "IMAGE")
: [];
}
},
mutations: {
setImageData(state:any, infopackImageData: any) {
state.infoPackCreationTab.infopackContents.filter((item: any) => {if(item.type === "IMAGE")
item = infopackImageData
console.log(item , 'this is items');
return item})
}
},
actions: {
setImageData(context: any, payload: any) {
context.commit('setImageData', payload)
}
}
and in my component I am using the computed to get the imageList:
computed: {
...mapGetters("creationStore", ["infoPackImage"]),
imageList: {
get() {
return this.infoPackImage ?? [];
},
set(value) {
this.$store.dispatch('creationStore/setImageData', value);
}
}
},
The problem is I want to edit a value of the imageList by index using draggable libarary,
but imageList does not act reactive and it just move the image and not showing the other image in the previous index:
async imageChange(e) {
this.loading = true
let newIndex = e.moved.newIndex;
let prevOrder = this.imageList[newIndex - 1]?.order ?? 0
let nextOrder = this.imageList[newIndex + 1]?.order ?? 0
const changeImageOrder = new InfopackImageService();
try {
return await changeImageOrder.putImageApi(this.$route.params.infopackId,
this.$route.params.tabId,
e.moved.element.id, {
title: e.moved.element.title,
infopackAssetRef: e.moved.element.infopackAssetRef,
order: nextOrder,
previousOrder: prevOrder,
}).then((res) => {
let image = {}
let infopackAsset = e.moved.element.infopackAsset
image = {...res, infopackAsset};
Vue.set(this.imageList, newIndex , image)
this.loading = false
return this.imageList
});
} catch (e) {
console.log(e, 'this is put error for tab change')
}
},
Array.prototype.filter doesn't modify an array in-place, it returns a new array. So this mutation isn't ever changing any state:
mutations: {
setImageData(state:any, infopackImageData: any) {
state.infoPackCreationTab.infopackContents.filter((item: any) => {if(item.type === "IMAGE")
item = infopackImageData
console.log(item , 'this is items');
return item})
}
},
So, if you intend to change state.infoPackCreationTab.infopackContents, you'll need to assign the result of filter():
mutations: {
setImageData(state:any, infopackImageData: any) {
state.infoPackCreationTab.infopackContents = state.infoPackCreationTab.infopackContents.filter(...)
However, since state.infoPackCreationTab did not have an infopackContents property during initialization, it will not be reactive unless you use Vue.set() or just replace the whole infoPackCreationTab object with a new one (see: Vuex on reactive mutations):
mutations: {
setImageData(state:any, infopackImageData: any) {
state.infoPackCreationTab = {
...state.infoPackCreationTab,
infopackContents: state.infoPackCreationTab.infopackContents.filter(...)
};
Hi I am trying to call a computed function inside a method function.
VueJs Code:
<script>
export default {
created() {
this.isDisabled(0);
},
data: function() {
return {
form: {
branch_office_id: null,
cashier_id: null,
gross_amount: '',
released_tickets: '',
start_ticket: '',
end_ticket: '',
z_inform_number: '',
created_at: '',
support: null,
error_end_bill_number_validation: ''
},
postsSelected: "",
branch_office_posts: [],
cashier_posts: []
}
},
methods: {
checkEndBillNumber() {
if(this.form.start_ticket > this.form.end_ticket) {
this.isDisabled(1);
this.$awn.alert("El número de boleta inicial no puede ser ", {labels: {success: "Error"}});
} else {
this.isDisabled(0);
}
}
},
computed: {
isDisabled(value) {
if(value == 0) {
return true;
} else {
return false;
}
}
}
}
</script>
I am trying to user isDisabled() function inside checkEndBillNumber() method function but when I do that it says:
[Vue warn]: Error in v-on handler: "TypeError: this.isDisabled is not a function"
So I wonder how can I use it? how can I do that? Thanks!
Computed properties as mentioned above are not functions. Hence passing arguments like isDisabled(value) wont work. But you can trick it to anonymously accept the value like this
computed: {
isDisabled() {
return (value) => {
if(value == 0) return true;
else return false;
}
}
}
This way you don't need a data property.
You do not have computed functions, but computed properties! So you have to store the value you want to use as a parameter in your computed property - e.g. in a data attribute, and then use that:
<script>
export default {
created() {
this.disabledParam = 0;
this.isDisabled; // Evaluates to "true" - what do you want with that result?
},
data: function() {
return {
form: {
branch_office_id: null,
cashier_id: null,
gross_amount: '',
released_tickets: '',
start_ticket: '',
end_ticket: '',
z_inform_number: '',
created_at: '',
support: null,
error_end_bill_number_validation: ''
},
postsSelected: "",
branch_office_posts: [],
cashier_posts: [],
disabledParam: null,
}
},
methods: {
checkEndBillNumber() {
if (this.form.start_ticket > this.form.end_ticket) {
this.disabledParam = 1;
this.isDisabled; // Evaluates to "false" - what to you want to do with that value?
this.$awn.alert("El número de boleta inicial no puede ser ", {labels: {success: "Error"}});
} else {
this.disabledParam = 0;
this.isDisabled; // Evaluates to "true" - what to you want to do with that value?
}
}
},
computed: {
isDisabled() {
if (this.disabledParam == 0) {
return true;
} else {
return false;
}
}
}
}
</script>
Also, please note that your calls to isDisabled(1) wouldn't so anything even if you could use them as functions. You should probably do something with the return values of isDisabled.
And you do not need computed properties in this way - in your example, you should simply create isDisabled(value) as another method and call that. But I guess your code is just an example, not your real code. Computed properties usually are being used as values in your template.
My example code is just there to illustrate how you can pass parameters into the code of computed properties. Besides that, your code has some issues.
Unexpected side effect in "filteredTeamsData" computed property
I have imported the two JSON file
import seasonList from '../assets/data/season_list.json'
import team data from '../assets/data/match_team.json'
Code -
export default {
name: 'SeasonSplit',
components: {
TableElement,
},
data () {
return {
selected: '1',
teamData: teamData,
teamList: [],
seasonList: seasonList,
filteredData: [],
tableColumns: ['toss_wins', 'matches', 'wins', 'losses', 'pts']
}
},
computed: {
filteredTeamsData: function () {
this.dataArr = []
this.filteredData = []
this.teamList = []
teamData.forEach(element => {
if(element.season == seasonList[this.selected-1]){
this.filteredData.push(element)
this.teamList.push(element.team)
this.dataArr.push(element.wins)
}
})
// console.log(this.filteredData)
return this.dataArr
}
}
}
I'd do it as follows:
export default {
name: 'SeasonSplit',
components: {
TableElement,
},
data () {
let filteredData = [];
let teamList = [];
let dataArr = [];
teamData.forEach(element => {
if(element.season == seasonList[this.selected-1]){
filteredData.push(element)
teamList.push(element.team)
dataArr.push(element.wins)
}
});
return {
selected: '1',
teamData: teamData,
teamList: teamList ,
seasonList: seasonList,
filteredData: filteredData ,
tableColumns: ['toss_wins', 'matches', 'wins', 'losses', 'pts'],
filteredTeamsData: dataArr
}
}
I would like to combine some filters in my Vue app:
app = new Vue({
el: '#app',
data: {
products: null,
productGroups: null,
productPackageWeights: null,
checkedProductGroupItems: [],
checkedProductPackageWeights: [],
},
created: function created() {
this.fetchData();
},
computed: {
productsFilter: function () {
return this.filterProductGroupItems;
}
},
methods: {
fetchData: function () {
var vm = this
axios.get([MY_JSON_FILE])
.then(function(response){
console.log(response.data.filter_data.product_package_weights);
vm.productPackageWeights = response.data.filter_data.product_package_weights;
vm.productGroups = response.data.filter_data.product_groups;
vm.products = response.data.products;
}).catch(function (error) {
alert('Het ophalen van de producten is niet gelukt');
});
},
filterProductGroupItems: function(data) {
if (this.checkedProductGroupItems.length == 0) return true;
return this.checkedProductGroupItems.includes(data.features.product_groups.value);
},
filterProductPackageWeights: function(data) {
if (this.checkedProductPackageWeights.length == 0) return true;
return this.checkedProductPackageWeights.includes(data.features.product_package_weights);
},
}
});
The code works only for the filterProductGroupItems. How can I combine the filterProductGroupItems and filterProductPackageWeights results in the computed productsFilter function? I'm also planning to make some more filter functions.
Please help
Thanks!
you can do this
computed: {
productsFilter: function () {
return [...this.filterProductGroupItems(), ...this.filterProductPackageWeights()];
}
},
or concat
computed: {
productsFilter: function () {
return this.filterProductGroupItems().concat(this.filterProductPackageWeights());
}
},
the problem may be that you could end up with an array that has [true, Obj, Obj ...] if one filter returns true, so you may want to change the filter to return an empty array
filterProductGroupItems: function(data) {
if (this.checkedProductGroupItems.length == 0) return [];
return this.checkedProductGroupItems.includes(data.features.product_groups.value);
},
filterProductPackageWeights: function(data) {
if (this.checkedProductPackageWeights.length == 0) return [];
return this.checkedProductPackageWeights.includes(data.features.product_package_weights);
},