How to filter a product list using v-btn in vuetify? - vue.js

I am currently trying to filter a list of objects by using buttons.
I know that both v-btn and v-card loops are not currently interdependent, but I am unable to figure out how to link both sections to properly show only the correct category when pressing its respective button.
Thanks for the help!
<v-row class="my-4">
<v-btn
v-for="category in categories"
text
class="underline"
route :to="category.route"
#click="category.function"
>{{ category.text }}</v-btn>
</v-row>
<v-row
justify="start">
<v-card
v-for="product in products"
:key="product.name"
class="ma-3 text-center">
<v-img
:src="product.src"
class="mc mt-2"
>
</v-img>
<v-card-title
class="bold justify-center">
<h4>{{ product.name }}</h4>
</v-card-title>
</v-card>
</v-row>
categories: [
{ text: 'All', function: "all()" },
{ text: 'Fruits & Veggies', function: "fruitsVeggies()" },
{ text: 'Baking', function: "baking" },
{ text: 'Gadgets', function: "gadgets" },
{ text: 'Cutting Boards', function: "cuttingBoards"}],
products: [{...}, {...}, etc]
computed: {
all() {
return this.products.filter(product => {
return product
})
},
fruitsVeggies() {
return this.products.filter(product => {
return product.category === 'Fruits & Veggies'
})
},
baking() {
return this.products.filter(product => {
return product.category === 'Baking'
})
},
cuttingBoards() {
return this.products.filter(product => {
return product.category === 'Cutting Boards'
})
}

Vue computed properties return a dynamic value
When you call baking as a function, it should throw an error in the console; it's not a function, but a property
Instead, you could define a computed property called filteredProducts that changes filter based on something stored in the data, and loop over that instead
data() {
productFilter: "all"
}
computed: {
// your computed values
filteredProducts() {
if (this.productFilter === "all") {
return this.all;
}
// etc. For all filters
}
}
Then in your template:
<v-row
justify="start"
>
<v-card
v-for="product in filteredProducts"

Related

Vue-multiselect prevent selecting any items when using Single select (object)

I'm using Vue-multiselect 2.1.4
It works like a charm when I use single select with array options. But in case of using single select with array of objects, all items are green and they are not selectable! (They have "is-selected" class)
To clarify the problem, I used the sample code from the project website and replace the options with my data.
<multiselect v-model="value" deselect-label="Can't remove this value"
track-by="name" label="name" placeholder="Select one"
:options="options" :searchable="false" :allow-empty="false">
<template slot="singleLabel" slot-scope="{ option }">
<strong>{{ option.name }}</strong> is written in
<strong> {{ option.language }}</strong>
</template>
</multiselect>
const config = {
data() {
return {
value: null,
options: []
}
},
async mounted() {
await this.getTerminals();
},
methods: {
async getTerminals() {
await window.axios.get("/api/Operation/GetTerminals")
.then(resp => {
this.$data.options = resp.data;
})
.catch(err => {
console.error(err);
});
},
}
};
const app = Vue.createApp(config);
app.component('Multiselect', VueformMultiselect);
app.mount('#app');
In case of array of objects, first you need to populate the values in object and then push the object in options array. And there will be few changes in the template as well. For example if your object is like this, following will work:
data(){
return{
value: null,
option: {
value: "",
name: "",
icon: "",
},
options: [],
}
},
methods: {
getData(){
//call your service here
response.data.list.forEach((item, index) => {
self.option.value = item.first_name + item.last_name;
self.option.name = item.first_name + " " + item.last_name;
self.option.icon =
typeof item.avatar !== "undefined" && item.avatar != null
? item.avatar
: this.$assetPath + "images/userpic-placeholder.svg";
self.options.push({ ...self.option });
});
}
}
Then in the template fill the options like this:
<Multiselect
v-model="value"
deselect-label="Can't remove this value"
track-by="value"
label="name"
:options="options"
:searchable="false"
:allow-empty="false"
>
<template v-slot:singlelabel="{ value }">
<div class="multiselect-single-label">
<img class="character-label-icon" :src="value.icon" />
{{ value.name }}
</div>
</template>
<template v-slot:option="{ option }">
<img class="character-option-icon" :src="option.icon" />
{{ option.name }}
</template>
</Multiselect>
Call your getData() function in created hook.
For me the solution was to use the "name" and "value" keys for my object. Anything else and it doesn't work (even if they use different keys in the documenation). This seems like a bug, but that was the only change I needed to make.

How to pass custom props to component in Vue from function?

I want to pass isReadonly boolean value from first component to second.
And it does not work.
Edited after cafertayyar answer.
Method isReadonly moved from methods to computed.
First component:
<template>
<PreliminaryInformationUsageCode :is-readonly="isReadonly" />
</template>
<script>
import PreliminaryInformationUsageCode from './form/PreliminaryInformationUsageCode.vue'
export default {
name: 'FormPage',
computed: {
form() {
return this.$store.getters['form/form']
},
isReadonly: function() {
//return true
return false
}
},
components: {
PreliminaryInformationUsageCode,
},
}
</script>
Second component:
<template>
<v-select
v-model="usageCodesSelected"
:items="usageCodes"
item-text="name"
item-value="code"
label="Label"
multiple
hint="Hint"
persistent-hint
v-bind:readonly="isReadonly"
>
<template v-slot:selection="{ item, index }">
<v-chip v-if="index === 0">
<span>{{ item.name }}</span>
</v-chip>
<span
v-if="index === 1"
class="grey--text text-caption"
>
(+{{ usageCodesSelected.length - 1 }} дополнительно)
</span>
</template>
</v-select>
</template>
<script>
export default {
name: 'PreliminaryInformationUsageCode',
props: {
isReadonly: {
Boolean
},
},
data: function() {
return {
usageCodesSelected: [
],
usageCodes: [
],
}
},
}
</script>
Use this:
<PreliminaryInformationUsageCode :is-readonly="isReadonly"/>
and instead of using isReadonly function, define a computed like:
computed: {
isReadonly() {
return this.form.status.seq != 10;
}
}

Cannot get computed property (array)

Trying to get a 'displayImages' array as a computed property. Using a default 'selected' property = 0.
this.selected changes accordingly on mouseover and click events.
When trying to get the computed 'displayImages' it says:
"this.variations[this.selected] is undefined."
I'm using an api to get my product data and images.
<template>
<div id="product-page">
<v-card width="100%" class="product-card">
<div class="image-carousel">
<v-carousel height="100%" continuos hide-delimiters>
<v-carousel-item
v-for="(image, i) in displayImages"
:key="i"
:src="image"
>
</v-carousel-item>
</v-carousel>
</div>
<div class="details">
<h2>{{ this.title }}<br />Price: ${{ this.price }}</h2>
<p>{{ this.details }}</p>
<ul style="list-style: none; padding: 0">
<li
style="border: 1px solid red; width: auto"
v-for="(color, index) in variations"
:key="index"
#mouseover="updateProduct(index)"
#click="updateProduct(index)"
>
{{ color.color }}
</li>
</ul>
<div class="buttons">
<v-btn outlined rounded
>ADD TO CART<v-icon right>mdi-cart-plus</v-icon></v-btn
>
<router-link to="/shop">
<v-btn text outlined rounded> BACK TO SHOP</v-btn>
</router-link>
</div>
</div>
</v-card>
</div>
</template>
<script>
export default {
name: "Product",
props: ["APIurl"],
data: () => ({
title: "",
details: "",
price: "",
variations: [],
selected: 0,
}),
created() {
fetch(this.APIurl + "/products/" + this.$route.params.id)
.then((response) => response.json())
.then((data) => {
//console.log(data);
this.title = data.title;
this.details = data.details.toLowerCase();
this.price = data.price;
data.variations.forEach((element) => {
let imagesArray = element.photos.map(
(image) => this.APIurl + image.url
);
this.variations.push({
color: element.title,
images: imagesArray,
qty: element.qty,
productId: element.productId,
});
});
});
},
computed: {
displayImages() {
return this.variations[this.selected].images;
},
},
methods: {
updateProduct: function (index) {
this.selected = index;
console.log(index);
}
},
};
</script>
To properly expand on my comment, the reason why you are running into an error is because when the computed is being accessed in the template, this.variations is an empty array. It is only being populated asynchronously, so chances are, it is empty when VueJS attempts to use it when rendering the virtual DOM.
For that reason, accessing an item within it by index (given as this.selected) will return undefined. Therefore, attempting to access a property called images in the undefined object will return an error.
To fix this problem, all you need is to introduce a guard clause in your computed as such:
computed: {
displayImages() {
const variation = this.variations[this.selected];
// GUARD: If variation is falsy, return empty array
if (!variation) {
return [];
}
return variation.images;
},
}
Bonus tip: if you one day would consider using TypeScript, you can even simplify it as such... but that's a discussion for another day ;) for now, optional chaining and the nullish coalescing operator is only supported by bleeding edge versions of evergreen browsers.
computed: {
displayImages() {
return this.variations[this.selected]?.images ?? [];
},
}
For avoid this kind of error, you must to use the safe navigation property.
Remember, it's useful just when the app is loading.
Try something like that:
<script>
export default {
name: 'Product',
computed: {
displayImages() {
if (this.variations[this.selected]) {
return this.variations[this.selected].images;
}
return [];
},
},
};
</script>

Prevent vuetify checkbox from checking itself?

I want the v-checkbox to remain unchanged after I write in the text field.
What is happening:
The checkbox checks itself whenever I click outside the box or type in the text field below.
What is expected:
The checkbox to remain unchecked until the use checks it.
Code:
export default {
props: ['answer'],
data() {
return {
newAnswer: 'Your answer here...',
multiChoiceAnswers: {
answers: ['test1', 'test2'],
selected: [],
}
}
},
created() {
if (this.answer.answers.length > 1) {
this.multiChoiceAnswers.answers = this.answer.answers
this.multiChoiceAnswers.selected = this.answer.selected
} else {
console.log('Answer Template Generated')
}
},
methods: {
selectedAnswer(clickEvent, index) {
console.log(clickEvent, index)
//Checking wether or not the answer is a value or null
//in order to push or remove it from the selected answers
if (clickEvent === this.multiChoiceAnswers.answers[index]) {
this.multiChoiceAnswers.selected.push(clickEvent)
} else {
const selectedPosition = this.multiChoiceAnswers.selected.indexOf(this.multiChoiceAnswers.answers[index])
this.multiChoiceAnswers.selected.splice(selectedPosition, selectedPosition + 1)
}
this.$emit('newAnswer', this.multiChoiceAnswers)
},
changedAnswer(changedAnswer, index) {
console.log(changedAnswer)
//Getting previous selected answer position to replace later
const selectedPosition = this.multiChoiceAnswers.selected.indexOf(this.multiChoiceAnswers.answers[index])
//Changing the current value of answer[index] to input value in answers
this.multiChoiceAnswers.answers.splice(index, index + 1, changedAnswer)
//Changing the current value of answer[index] to input value in selected
this.multiChoiceAnswers.selected.splice(selectedPosition, selectedPosition + 1, changedAnswer)
this.$emit('newAnswer', this.multiChoiceAnswers)
},
Here is the template code:
<v-container>
<div :key="(answer, index)" v-for="(answer, index) in multiChoiceAnswers.answers">
<v-layout align-center>
<v-checkbox hide-details class="shrink mr-2" #click.prevent #change="selectedAnswer($event, index)" :value="answer"></v-checkbox>
<v-text-field class="checkbox-input" #input="changedAnswer($event, index)" :placeholder="answer"></v-text-field>
<v-btn #click="removeAnswer(index)">Remove</v-btn>
</v-layout>
</div>
</v-container>
Seems like I must have been to tired or drunk when I posted this ;)
Here is the completely new revised code I did to fix this solution:
<template>
<div>
<v-container>
<div :key="(answer, index)" v-for="(answer, index) in multiChoiceAnswers.answers">
<v-layout align-center>
<v-checkbox hide-details class="shrink mr-2" v-model="answer.selected"></v-checkbox>
<v-text-field class="checkbox-input" v-model="answer.answerText" :placeholder="answer.answerText"></v-text-field>
<v-btn #click="removeAnswer(index)">Remove</v-btn>
</v-layout>
</div>
</v-container>
<v-btn #click="newAnswerOption">Add Answer</v-btn>
</div>
<script>
export default {
props: ['answer'],
data() {
return {
newAnswer: { answerText: 'Your answer here...', selected: false },
multiChoiceAnswers: {
answers: [
{ answerText: 'test1', selected: false },
{ answerText: 'test2', selected: false }
],
},
}
},
created() {
if (this.answer.answers.length > 1) {
this.multiChoiceAnswers.answers = this.answer.answers
} else {
console.log('Answer Template Generated')
}
},
methods: {
newAnswerOption() {
this.multiChoiceAnswers.answers.push(this.newAnswer)
this.$emit('newAnswer', this.multiChoiceAnswers)
},
removeAnswer(index) {
//Removing the answer
this.multiChoiceAnswers.answers.splice(index, 1)
this.$emit('newAnswer', this.multiChoiceAnswers)
}
}
}
</script>
What has changed?
I deleted all the previous code that was broken and necessarily complex.
I created a new data array with the objects answers. Each object now has the answerText (string) and the selected (boolean).
The checkbox is now connected to change the answers.selected with v-model
The input is now connected to change the answers.answerText with v-model

vuetify autocomplete allow unknown items between chips

I am trying to modify the sample code at https://vuetifyjs.com/en/components/autocompletes#example-scoped-slots to allow arbitrary content not matching any autocomplete items in between chips (so user can tag other users in a message similar to slack and facebook)
So for example, the user could type "Sandra" and then select "sandra adams", then type "foo" and then type another space and start typing "John" and the autcomplete would pop up again and allow the user to select "John Smith".
I've been through all the properties in the docs and there doesn't seem to be support for this built in.
I tried using custom filtering to ignore the irrelevant parts of the message when displaying autocomplete options, but the autocomplete seems to remove non-chip content when it loses focus and I can't see a property that allows me to prevent this behavior.
not sure if the autcomplete is the thing to be using or if I would be better off hacking combo box to meet this requirement, because this sample seems closer to what I'm tryng to do https://vuetifyjs.com/en/components/combobox#example-no-data, but then I believe I lose the ajax capabilities that come with automcomplete.
You can achieve this by combining the async search of the autocomplete with the combobox.
For example:
new Vue({
el: '#app',
data: () => ({
activator: null,
attach: null,
colors: ['green', 'purple', 'indigo', 'cyan', 'teal', 'orange'],
editing: null,
descriptionLimit: 60,
index: -1,
nonce: 1,
menu: false,
count: 0,
model: [],
x: 0,
search: null,
entries: [],
y: 0
}),
computed: {
fields () {
if (!this.model) return []
return Object.keys(this.model).map(key => {
return {
key,
value: this.model[key] || 'n/a'
}
})
},
items () {
return this.entries.map(entry => {
const Description = entry.Description.length > this.descriptionLimit
? entry.Description.slice(0, this.descriptionLimit) + '...'
: entry.Description
return Object.assign({}, entry, { Description })
})
}
},
watch: {
search (val, prev) {
// Lazily load input items
axios.get('https://api.publicapis.org/entries')
.then(res => {
console.log(res.data)
const { count, entries } = res.data
this.count = count
this.entries = entries
})
.catch(err => {
console.log(err)
})
.finally(() => (this.isLoading = false))
/*if (val.length === prev.length) return
this.model = val.map(v => {
if (typeof v === 'string') {
v = {
text: v,
color: this.colors[this.nonce - 1]
}
this.items.push(v)
this.nonce++
}
return v
})*/
},
model (val, prev) {
if (val.length === prev.length) return
this.model = val.map(v => {
if (typeof v === 'string') {
v = {
Description: v
}
this.items.push(v)
this.nonce++
}
return v
})
}
},
methods: {
edit (index, item) {
if (!this.editing) {
this.editing = item
this.index = index
} else {
this.editing = null
this.index = -1
}
},
filter (item, queryText, itemText) {
const hasValue = val => val != null ? val : ''
const text = hasValue(itemText)
const query = hasValue(queryText)
return text.toString()
.toLowerCase()
.indexOf(query.toString().toLowerCase()) > -1
}
}
})
<link href='https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900|Material+Icons' rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js" integrity="sha256-mpnrJ5DpEZZkwkE1ZgkEQQJW/46CSEh/STrZKOB/qoM=" crossorigin="anonymous"></script>
<div id="app">
<v-app>
<v-content>
<v-container>
<v-combobox
v-model="model"
:filter="filter"
:hide-no-data="!search"
:items="items"
:search-input.sync="search"
hide-selected
label="Search for an option"
:allow-overflow="false"
multiple
small-chips
solo
hide-selected
return-object
item-text="Description"
item-value="API"
:menu-props="{ closeOnClick: false, closeOnContentClick: false, openOnClick: false, maxHeight: 200 }"
dark
>
<template slot="no-data">
<v-list-tile>
<span class="subheading">Create</span>
<v-chip
label
small
>
{{ search }}
</v-chip>
</v-list-tile>
</template>
<template
v-if="item === Object(item)"
slot="selection"
slot-scope="{ item, parent, selected }"
>
<v-chip
:selected="selected"
label
small
>
<span class="pr-2">
{{ item.Description }}
</span>
<v-icon
small
#click="parent.selectItem(item)"
>close</v-icon>
</v-chip>
</template>
<template
slot="item"
slot-scope="{ index, item, parent }"
>
<v-list-tile-content>
<v-text-field
v-if="editing === item.Description"
v-model="editing"
autofocus
flat
hide-details
solo
#keyup.enter="edit(index, item)"
></v-text-field>
<v-chip
v-else
dark
label
small
>
{{ item.Description }}
</v-chip>
</v-list-tile-content>
</template>
</v-combobox>
</v-container>
</v-content>
</v-app>
</div>
so I ended up building a renderless component that is compatible with vuetify as it goes through the default slot and finds any of the types of tags (textarea, input with type of text, or contenteditable) that tribute supports, and allows you to put arbitrary vue that will be used to build the tribute menu items via a scoped slot.
in future might try to wrap it as a small NPM package to anyone who wants a declarative way to leverage tribute.js for vue in a more flexible way than vue-tribute allows, but for now here's my proof of concept
InputWithMentions.vue
<script>
import Tribute from "tributejs"
// eslint-disable-next-line
import * as css from "tributejs/dist/tribute.css"
import Vue from "vue"
export default {
mounted() {
let menuItemSlot = this.$scopedSlots.default
let tribute = new Tribute({
menuItemTemplate: item =>
{
let menuItemComponent =
new Vue({
render: function (createElement) {
return createElement('div', menuItemSlot({ menuItem: item }))
}
})
menuItemComponent.$mount()
return menuItemComponent.$el.outerHTML
},
values: [
{key: 'Phil Heartman', value: 'pheartman'},
{key: 'Gordon Ramsey', value: 'gramsey'}
]})
tribute.attach(this.$slots.default[0].elm.querySelectorAll('textarea, input[type=text], [contenteditable]'))
},
render(createElement) {
return createElement('div', this.$slots.default)
}
}
</script>
User.vue
<InputWithMentions>
<v-textarea
box
label="Label"
auto-grow
value="The Woodman set to work at once, and so sharp was his axe that the tree was soon chopped nearly through.">
</v-textarea>
<template slot-scope="{ menuItem }">
<v-avatar size="20" color="grey lighten-4">
<img src="https://vuetifyjs.com/apple-touch-icon-180x180.png" alt="avatar">
</v-avatar>
{{ menuItem.string }}
</template>
</InputWithMentions>