Filter Vue list based on select option value - vuejs2

I try to filter my list with 2 select lists based on the selected value. It seems like my computed filter is not working?
You should be able to filter the list on 'Price from' and 'Price to'
List.vue
My computed filter property:
filteredData() {
const LowerCaseSearch = this.search.toLowerCase();
return this.products.filter(
product =>
(product.name.toLowerCase().includes(LowerCaseSearch) ||
product.category.toLowerCase().includes(LowerCaseSearch)) &&
(!this.checked.length || this.checked.includes(product.category)) &&
(!this.selectedFrom.length || this.selectedFrom.includes(product.price)) &&
(!this.selectedTo.length || this.selectedTo.includes(product.price))
);
},
In my registered component I use v-model to bind to the computed property selectedFrom
<Price v-model="selectedFrom" />
How do I bind to the other property selectedTo in one v-model and what's wrong with my filter?
I also use a prefix 'From' and 'To' to put in front of the options.
data: () => {
return {
selectedFrom: '0,00',
priceFrom: [
{ prefix: 'From', text: '0,00', value: '0,00' },
{ prefix: 'From', text: '200,00', value: '200,00' },
{ prefix: 'From', text: '400,00', value: '400,00' }
],
selectedTo: 'No max',
priceTo: [
{ prefix: 'To', text: '400,00', value: '400,00' },
{ prefix: 'To', text: '600,00', value: '600,00' },
{ prefix: 'To', text: '800,00', value: '800,00' },
{ text: 'No max', value: 'No max' }
]
}
},
Is there a more elegant and D.R.Y way to do this?
Here is a sandbox what I have so far.

You should bind an object to your v-model on the <price> component.
This way you can pass multiple values to and from your component, without having to use multiple props.
I would also suggest you convert your value in your selects to numbers, so it's easier to use them to compare to your prices.
You've also defined data properties and computed properties in the sandbox (<price> component) with the same name, this is not possible. So you should remove the data properties and stick to the computed ones to handle your data.
Fork of your sandbox with my suggested changes.

Related

In vue, how do I filter a data object to only show values from the last 24 hours?

I have an array with some data objects that were created on various dates. I would like to only display the objects that were created within the last 24 hours.
I have tried to use moment for this, by using subtract on the date values, but it has no effect. Maybe someone here could come up with a suggestion.
Here are my computed properties. I use these because I am outputting the data in a bootstrap table, so the "key" represents the different values inside the object.
My table:
<b-card class="mt-4 mb-4">
<b-table
:items="tasks"
:fields="fields"
sort-desc
/>
</b-card>
My array (I am actually importing from a database, but for this question I will just write it manually) Please note I am just showing a single object here. In reality I have hundreds of objects
data: {
tasks: [
{ message: 'Foo' },
{ creationDateTime: '03-02-2022' },
{ isRead: false }
]
}
In my computed properties I then pass them to the table
computed: {
fields() {
return [
key: 'message',
label: 'message'),
sortable: true,
},
{
key: 'creationDateTime',
label: 'Date created',
formatter: date => moment(date).subtract(24, 'hours').locale(this.$i18n.locale).format('L'),
sortable: true,
},
{
key: 'isRead',
label: 'Has been read'),
sortable: true,
}
]
},
},
As I said, using subtract does not work. It still shows all objects in my database
I tried doing the reduction on the whole array as well, but I just get the error:
"TypeError: this.list.filter is not a function"
newTasks(){
if(this.tasks){
return moment(this.tasks.filter(task => !task.done)).subtract(24, 'hours')
}
}
I'm out of ideas.
In Moment, you can check if a date is within the last 24 hours with:
moment().diff(yourDate, 'hours') < 24
(note that future dates will also pass this check, but you can easily adjust it).
You can put this into your computed property:
newTasks(){
if(!this.tasks){
return []
}
return this.tasks.filter(task => !task.done && moment().diff(task.creationDateTime, 'hours') < 24)
}
And that's it, now newTasks should contain all tasks from the last 24 hours that are not done.

How to use $t from vue-i18n inside Vuex store to initialize static strings

In my vuex store module I have provinceData to supply as datasource for Vuetify dropdown selection box.
provinceData: [
{value:"AB", text: "Alberta"},
{value:"BC", text: "British Columbia"},
...
],
I can import i18n from '../plugins/i18n' and confirm in console output that i18n.t('province.BC') return me proper text from resource files
i18n.t('province.BC') British Columbia
click onLanguageChange fr
i18n.t('province.BC') British Columbia (Fr)
But how I can insert these translations into datasource?
provinceData: [
{value:"AB", text: ???i18n.t('province.AB')??? },
{value:"BC", text: ???i18n.t('province.BC')??? },
...
]
Now I realized what mistake I did by wrapping i18n.t('province.AB') into back ticks. Here is corrected version which render english only messages:
provinceData: [
{value:"AB", text: i18n.t('province.AB') },
{value:"BC", text: i18n.t('province.BC') },
...
]
Moreover, will it be reinitialized if I switch the current locale?
PS. When getter for this datasource is hit I can see that message retrieved according to current locale. But dropdown box izn't reloaded. That's the problem
Following getter print correct translation every time it called:
provinceData: (state) => {
console.log("i18n.t('province.BC')",i18n.t('province.BC'));
return state.provinceData;
},
Because the provinceData inside the store it can't be modified by anything but mutators.
So I decided to create this array right in the getter and it turns out to be quite fast.
provinceData: ( state ) =>
{
const provinceData = [ "AB", "BC", "MB", "NB", "NF", "NT", "NS", "NU", "ON", "PE", "QC", "SK", "YT" ];
let provinces = [];
provinceData.forEach( (province) => {
provinces.push
({
value : province,
text : i18n.t( 'province.'+province )
})
})
return provinces;
}

How to select specific fields on FaunaDB Query Language?

I can't find anything about how to do this type of query in FaunaDB. I need to select only specifics fields from a document, not all fields. I can select one field using Select function, like below:
serverClient.query(
q.Map(
q.Paginate(q.Documents(q.Collection('products')), {
size: 12,
}),
q.Lambda('X', q.Select(['data', 'title'], q.Get(q.Var('X'))))
)
)
Forget the selectAll function, it's deprecated.
You can also return an object literal like this:
serverClient.query(
q.Map(
q.Paginate(q.Documents(q.Collection('products')), {
size: 12,
}),
q.Lambda(
'X',
{
title: q.Select(['data', 'title'], q.Get(q.Var('X')),
otherField: q.Select(['data', 'other'], q.Get(q.Var('X'))
}
)
)
)
Also you are missing the end and beginning quotation marks in your question at ['data, title']
One way to achieve this would be to create an index that returns the values required. For example, if using the shell:
CreateIndex({
name: "<name of index>",
source: Collection("products"),
values: [
{ field: ["data", "title"] },
{ field: ["data", "<another field name>"] }
]
})
Then querying that index would return you the fields defined in the values of the index.
Map(
Paginate(
Match(Index("<name of index>"))
),
Lambda("product", Var("product"))
)
Although these examples are to be used in the shell, they can easily be used in code by adding a q. in front of each built-in function.

How to display RadDataForm Valueproviders with key value pair

I resolve most of my problem only few left out of which this one is preventing me to submit the form. I am using Nativescript + vue and without Typescript. how to display the Valueproviders with array list? Here is the code
https://play.nativescript.org/?template=play-vue&id=2oWObE
There was the problem with your data type. As per the documentation Array should have key and label properties. But still if you want id and name then you should try like below.
'valuesProvider': {
key: 'id',
label: 'name',
items: [
{ id: 1121, name: 'Shanghai' },
{ id: 3651, name: 'Lagos' },
{ id: 5213, name: 'Moscow' },
{ id: 6214, name: 'São Paulo' },
{ id: 6985, name: 'Sydney' }
]
};
https://docs.nativescript.org/vuejs/ns-ui/DataForm/dataform-editors-providers
Anyway, I tried that and that was not working for me either then searched for it and relaised that there is an open feature request to support the valuesProvider for picker from JSON metadata. You can vote to support the same feature.
https://github.com/NativeScript/nativescript-ui-feedback/issues/369
Solution
Just get you cityList out of vue data and map your data
https://play.nativescript.org/?template=play-vue&id=2oWObE&v=6
more detailed version with groups
https://play.nativescript.org/?template=play-vue&id=rqK7wO&v=3

How to set defaultValue for multi select?

So, I need to pass defaultValue to a react-select component with enabled multi select. I've tried everything I could think of: array of strings, array of objects, string, etc... Nothing seems to work.
I'm also using the getOptionLabel and getOptionValue, might they be the cause for all this mess?
If you refer to react-select documentation, the way to set defaultValue to multiple value select:
<Select
defaultValue={[colourOptions[2], colourOptions[3]]}
isMulti
name="colors"
options={colourOptions}
className="basic-multi-select"
classNamePrefix="select"
/>
The structure of options is
[
{
label: <string>,
value: <string>,
}
]
Working example here.
There is an alternate way to use value as your defaultValue.
In my case I have used "id" and "industry" instead of "label" and "value"
this.state = {
interested_industries: [{id:"ANY", industry:"ANY"}]
}
And in Select component:-
<Select
name="interested_industries"
options={industries}
value={interested_industries}
getOptionLabel={ x => x.id}
getOptionValue={ x => x.industry}
onChange={this.handleSelect}
isMulti
/>
defaultValue accepts an object or array of objects.
here an object can be like this :
defaultValue = {{ value: 0, label: "John" }}
This is also one way:
defaultValue = { array1[0] }
If you want array of objects for multiple options (isMulti) you can do this:
defaultValue = { array1.map(ele => ele) }
Where array1 is an array of objects.
array1 = [
{ label: "John", value: 0 },
{ label: "Indiana", value: 1 },
{ label: "Stark", value: 2 },
];
This solution worked for me. I hope this helps you too.
You can set defaultValue without index
<Select
defaultValue={existingItems}
onChange={(option) => onChangeSelect(option)}
closeMenuOnSelect={false}
components={animatedComponents}
isMulti={true}
options={options}
/>
But for this to work you need await loading items from defaultValue if you loading from server
For Example my full code
{!kindsByRestaraunt.loading ? (
<Select
defaultValue={existingItems}
onChange={(option) => onChangeSelect(option)}
closeMenuOnSelect={false}
components={animatedComponents}
isMulti={true}
options={options}
/>
): ""}
According to React documentation, you can do this:
<select multiple={true} value={['B', 'C']}>
Where B, C are the default value you want to have selected.