Render block in v-for over object only once vue.js? - vue.js

I have an object with this structure
object: {
"prop1": [],
"prop2": [],
"prop3": [],
}
In my template I want to loop over it and display data in prop's but if there is no data in any of them I want to show something like this
<div>No data</div>
but only once and not for each prop
So far I have this
<div v-for="(props, index) in object" :key="index">
<div v-if="!props.length">
No data
</div>
</div>
But it shows message 3 times, for each prop.
I'm not sure how to solve it. Any help will be much appreciated.

To solve this in a nice way, you should use a computed property.
A computed property is basically a piece of code that give meaningless caclulations meaningful names.
export default {
data() {
return {
object: {
"prop1": [],
"prop2": [],
"prop3": [],
},
};
},
computed: {
areAllEmpty() {
return Object.values(this.object).map(e => e.length).reduce((a, b) => a + b, 0) === 0;
},
}
};
This can then be used in your template as the following:
<template>
<template v-if="areAllEmpty">
<div>No data</div>
</template>
<template v-else>
<div v-for="(props, index) in object" :key="index">
I'm index {{ index }} with length {{ props.length }}
</div>
</template>
</template>

Related

How do have unique variables for each dynamically created buttons/text fields?

I'm trying to create buttons and vue element inputs for each item on the page. I'm iterating through the items and rendering them with v-for and so I decided to expand on that and do it for both the rest as well. The problem i'm having is that I need to to bind textInput as well as displayTextbox to each one and i'm not sure how to achieve that.
currently all the input text in the el-inputs are bound to the same variable, and clicking to display the inputs will display them all at once.
<template>
<div class="container">
<div v-for="(item, index) in items" :key="index">
<icon #click="showTextbox"/>
<el-input v-if="displayTextbox" v-model="textInput" />
<el-button v-if="displayTextbox" type="primary" #click="confirm" />
<ItemDisplay :data-id="item.id" />
</div>
</div>
</template>
<script>
import ItemDisplay from '#/components/ItemDisplay';
export default {
name: 'ItemList',
components: {
ItemDisplay,
},
props: {
items: {
type: Array,
required: true,
},
}
data() {
displayTextbox = false,
textInput = '',
},
methods: {
confirm() {
// todo send request here
this.displayTextbox = false;
},
showTextbox() {
this.displayTextbox = true;
}
}
}
</script>
EDIT: with the help of #kissu here's the updated and working version
<template>
<div class="container">
<div v-for="(item, index) in itemDataList" :key="itemDataList.id">
<icon #click="showTextbox(item.id)"/>
<El-Input v-if="item.displayTextbox" v-model="item.textInput" />
<El-Button v-if="item.displayTextbox" type="primary" #click="confirm(item.id)" />
<ItemDisplay :data-id="item.item.uuid" />
</div>
</div>
</template>
<script>
import ItemDisplay from '#/components/ItemDisplay';
export default {
name: 'ItemList',
components: {
ItemDisplay,
},
props: {
items: {
type: Array,
required: true,
},
}
data() {
itemDataList = [],
},
methods: {
confirm(id) {
const selected = this.itemDataList.find(
(item) => item.id === id,
)
selected.displayTextbox = false;
console.log(selected.textInput);
// todo send request here
},
showTextbox(id) {
this.itemDataList.find(
(item) => item.id === id,
).displayTextbox = true;
},
populateItemData() {
this.items.forEach((item, index) => {
this.itemDataList.push({
id: item.uuid + index,
displayTextbox: false,
textInput: '',
item: item,
});
});
}
},
created() {
// items prop is obtained from parent component vuex
// generate itemDataList before DOM is rendered so we can render it correctly
this.populateItemData();
},
}
</script>
[assuming you're using Vue2]
If you want to interact with multiple displayTextbox + textInput state, you will need to have an array of objects with a specific key tied to each one of them like in this example.
As of right now, you do have only 1 state for them all, meaning that as you can see: you can toggle it for all or none only.
You'll need to refactor it with an object as in my above example to allow a case-per-case iteration on each state individually.
PS: :key="index" is not a valid solution, you should never use the index of a v-for as explained here.
PS2: please follow the conventions in terms of component naming in your template.
Also, I'm not sure how deep you were planning to go with your components since we don't know the internals of <ItemDisplay :data-id="item.id" />.
But if you also want to manage the labels for each of your inputs, you can do that with nanoid, that way you will be able to have unique UUIDs for each one of your inputs, quite useful.
Use an array to store the values, like this:
<template>
<div v-for="(item, index) in items" :key="index">
<el-input v-model="textInputs[index]" />
</div>
<template>
<script>
export default {
props: {
items: {
type: Array,
required: true,
},
},
data() {
textInputs: []
}
}
</script>

How to register an array of objects with v-model? Vue 2

The first time that I dive into making this type of form with Vue, the issue is that I can't think of how to save the data inside the foreach that I generate with axios.
Where I would like to save the ID and the option selected with the input select as an object in order to make faster the match in the backend logic.
<template>
<div class="row" v-else>
<div class=" col-sm-6 col-md-6 col-lg-6" v-for="(project, index) in projects" :key="index">
<fieldset class="border p-2 col-11">
<legend class="w-auto col-12">Proyecto: {{project.name}}</legend>
<b-form-group
id="user_id"
label="Reemplazante"
>
<b-form-select
v-model="formProject[index].us"
:options="project.users"
value-field="replacement_user_id"
text-field="replacement_user_name"
#change="addReemplacemet($event,project.id)"
>
<template v-slot:first>
<b-form-select-option value="All">Seleccione</b-form-select-option>
</template>
</b-form-select>
<input type="hidden" name="project" v-model="formProject[index].proj">
</b-form-group>
</fieldset>
</div>
</div>
</template>
<script>
import skeleton from './skeleton/ProjectUserSkeleton.vue'
export default {
name: 'ProjectsUser',
components: { skeleton },
props:{
user: { type: String },
},
data() {
return {
user_id: null,
showProject: false,
projects: [],
loadingProjects: true,
formProject: [
{
us: 'All',
proj: null
}
]
}
},
watch: {
user: function() {
this.viewProjects(this.user)
}
},
methods: {
async getProjects(salesman){
this.loadingProjects = true
await axios.get(route('users.getProjects'),{
params: {
filter_user: salesman
}
})
.then((res)=>{
this.projects = res.data.data
setTimeout(() => {
this.loadingProjects = false
}, 800);
})
},
This is the form:
This is the message error:
At first glance, this looks like an issue with data. Your error suggests that you're trying to read an undefined variable.
It's often undesirable to use an index from iterating one array on another. In your Vue code, the index is projects, but you use it to access the variable formProject. This is usually undesirable because you can no longer expect that index to reference a defined variable (unless you're referencing the array you are currently iterating).
The easiest solution, for now, is to make sure the arrays are of the same length. Then utilizing v-if or other methods to not render the snippet if the variable is not defined.
A more complicated but better solution is restructuring your data such that formProject exists in projects

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.

Vuetify v-data table get Index

Hey there I am new to vue js and vuetify.In my editProductSave I want to pass another variable which is the index of the row in the table. This is my current code and how would i achieve that? The table is plotted using the vuetify v-data-table
Whole code
<template>
<v-card>
<v-data-table
:headers="tableFields"
:items="programs"
:items-per-page="5">
<template v-slot:[`item._id.$oid`]="{ item }">
{{item._id.$oid}}
</template>
<template v-slot:[`item.tags`]="props">
<v-edit-dialog
:return-value.sync="props.item.tags"
large
persistent
#save="editProductSave(props.item)">
<div>{{props.item.tags.length === 0 ? '' : props.item.tags}}</div>
<template v-slot:input>
<div class="mt-1 text-h2">
Update Tag
</div>
<v-text-field
v-model="props.item.tags"
label="Edit"
single-line
counter
autofocus
></v-text-field>
</template>
</v-edit-dialog>
</template>
<script>
import tdmApi from "../services/api/Database";
export default {
props: ["DatabaseList"],
computed: {
totalRows() {
return this.programs.length;
},
},
created () {
this.viewTdmDatabase();
},
data () {
return {
tableFields: [
{text:'ID',value:'_id.$oid'},
{text:'Tag',value:'tags'},
],
programs: [],
}
},
</script>
<template v-slot:item.tags="{item,index}">
{{index}} //Output index
</template>
The code above should work, make sure to cover it with object.
Try the below code:
<template v-slot:[`item.tags`]="{props, index}">
<v-edit-dialog
:return-value.sync="props.item.tags"
large persistent
#save="editProductSave(props.item, index)">
// ...
</v-edit-dialog>
</template>
And in script the method would be
methods: {
editProductSave(item, index) {
// ...
}
}
It seems that vuetify does not have in the v-data-table api the index field, so in order to get it you can change the structure of the v-data-table.
This is an example of how to get the index of each row.
https://www.codegrepper.com/code-examples/whatever/vuetify+v-data-table+get+row+index
You can simply add the index to the programs in a computed property and import it in the data table like so:
template
...
<v-data-table
:headers="tableFields"
:items="programsComputed"
...
script
export default {
...
computed: {
totalRows() {
return this.programs.length;
},
programsComputed () {
return this.programs.map((program, index) => {
program.index = index;
return program;
})
}
},
...
data () {
return {
tableFields: [
{text:'ID',value:'_id.$oid'},
{text:'Tag',value:'tags'},
],
programs: [],
}
},
In your editProductSave(item) you would just have to call item.index

Vue - Unable to use variable in template

I have this code in my VUE file:
<template>
<div class="row">
<div class="col-12">
<section class="list">
<draggable class="drag-area" :list="picsNew" :options="{animation:200, group:'status'}" :element="'article'" #add="onAdd($event, false)" #change="update">
<article class="card" v-for="(photo, index) in picsNew" :key="photo.id" :data-id="photo.id">
<header>
{{ this.galCode }}{{ photo.filename }}
</header>
</article>
</draggable>
</section>
</div>
</div>
</template>
<script>
import draggable from 'vuedraggable'
export default {
components: {
draggable
},
props: ['myPics', 'galId', 'phCode', 'galCode'],
data() {
return {
picsNew: this.myPics,
}
},
methods: {
update() {
this.picsNew.map((photo, index) => {
photo.order = index + 1;
});
let photos = this.picsNew;
console.log(this.galCode)
axios.put('/gallery/' + this.galId + '/updateAll', {
photos: photos
}).then((response) => {
console.log(response.data);
}).catch((error) => {
console.log(error);
})
}
}
}
</script>
in the template, photo.filename works, but this.galCode throws these two errors:
app.js:44152 [Vue warn]: Error in render: "TypeError: Cannot read property 'galCode' of undefined"
found in
---> <DraggablePic> at resources/js/components/draggablepic.vue
app.js:45415 TypeError: Cannot read property 'galCode' of undefined
The variable contains a value, as i am printing it to console. What am I doing wrong?
The problem is that you try to access props variable directly from your template. To solve this, initalize a state variable (under data {}) Within props value as default like you did With picsNeW.
another remark, avoid to use "this" from template, you should access directly datas form its name. Use default value in your props, this is recommended :)
The line {{ this.galCode }}{{ photo.filename }} should be {{ galCode }}{{ photo.filename }}. Your problem is the this you added
First you should define Default value as :
props: {
name: {
type: String,
default: 'default'
},
...
galCode: {
type: Number,
default: 0
},
},
Second be sure you receive desired data, specially in nested object you should check the object defined to prevent receive undefined property error, like use v-if :
<header>
<template v-if="galCode">{{ galCode }}</template> // can use v-else here too print default value
<template v-if="photo.filename"> {{ photo.filename }}</template>
</header>