how to render array stored in vuex - vue.js

I am trying to render array of objects stored in store in the form of cards. But, I am not able to. Since it shows typeError.
It states
"error in render: "TypeError: Cannot read property 'item' of undefined"
I tried using this keyword and shifting the code to mounted() hook.
But, the error keeps on showing.
Here is the code:
CardRenderer.vue:
<template lang="html">
<div>
<b-container class="bv-example-row">
<b-row v-for="(row, i) in this. rows" v-bind:key="i">
<b-col v-for="(item, j) in row" v-bind:key="j" >
<!-- you card -->
<b-card
:title="item.title"
img-src="item.icon"
img-alt="Image"
img-top
tag="article"
style="max-width: 20rem;"
class="mb-2"
>
<b-card-text>
<h1>{{item.name}}</h1>
<pre>{{item.description}}</pre>
</b-card-text>
<b-button :href="'/dashboard/'+this.item.name" variant="primary">More</b-button>
</b-card>
</b-col>
</b-row>
</b-container>
</div>
</template>
<script lang="js">
export default {
name: 'CardRenderer',
props: {
},
data() {
return {
// rows: []
}
},
mounted() {
},
methods: {
},
computed: {
rows() {
const itemsPerRow = 3
var rows = []
let arr = this.$store.getters.responseAPI.apps
// eslint-disable-next-line
console.log(arr)
for (let i = 0; i < arr.length; i += itemsPerRow){
let row = []
for (let z = 0; z < itemsPerRow; z++) {
row.push(arr[z])
}
rows.push(row)
}
// eslint-disable-next-line
// console.log(this.rows)
return rows[0]
}
}
}
</script>
<style scoped>
</style>
This is how the error looks like.
and this is how the rows object looks like
How do i remove the error and the render the card.
I would love to have the changed code as the answer.
Thanks :)

I think you have a mistake at the computed property return statement.
Try replacing return rows[0] to return rows to return an array instead of the first item :)
I've finally caught an error))
This is my code sample at sandbox: https://codesandbox.io/embed/vue-template-sm0yx
You've got a mistake at the template, just remove this from :href="'/dashboard/'+this.item.name" to make it look like this: :href="'/dashboard/'+item.name"
That should work!))

Related

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

Update properties of component in Vue.js

I've been searching for the answer 2nd day. But still couldn't find solution.
I have the modal window template. And the main page template from where I need to update modal window size by clicking on the button (span). Shortly it's like this for HTML:
<template id="modal">
<div>
<div :class="'modal-' + size">
...
</div>
</div>
</template>
<template id="list">
<div>
<span #click="onDetails">
Show Details
</span>
</div>
<modal size="md" #showdetails="showdetails();" ref="modal">
...
</modal>
</template>
And for JS:
Vue.component("modal", {
template: "#modal",
props: {
size: {
type: String,
default: ""
}
},
methods: {
onDetails() {
this.$emit("showdetails")
}
}
})
var List = Vue.extend({
template: "#list",
methods: {
showDetails() {
if(this.$refs.modal.size == "md") {
this.$refs.modal.size = "lg"
}
<additional code here>
}
}
})
When I'm accessing this.$refs.modal.size for read - it's OK. When I'm just changing it from showDetails - OK if only this action in the function. When I'm put something else instead of - size is not updating.
For example:
this.$refs.modal.size = "lg" - will work
this.$refs.modal.theme = "danger"; this.$refs.modal.size = "lg" - neither of them are updating
What am I doing wrong?
You need to assign the attribute value of Size by the javascript method setAttribute . Example : this.$refs.modal.setAttribute('size', 'lg')
There is a working demo below:
new Vue({
el: '#app',
methods: {
showdetails() {
console.log(this.$refs.modal.getAttribute('size'));
this.$refs.modal.setAttribute('size', 'lg')
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.15/vue.js"></script>
<div id='app'>
<button size="md" #click="showdetails" ref="modal">Click</button>
</div>

Passing Array as prop not received on the other component

I am trying to pass an array of objects as a prop to a component. The Array is being passed without an array. I am neither receiving any compilation error.
I tried actually looking on to the object tried some stuff. But it did not work
Here is the code:
CardRenderer.vue:
<template lang="html">
<div>
<b-container class="bv-example-row">
<b-row v-for="(row, i) of rows" v-bind:key="i">
<b-col v-for="(item, j) of row" v-bind:key="j" >
<!-- you card -->
<b-card
:title="item.title"
img-src="item.icon"
img-alt="Image"
img-top
tag="article"
style="max-width: 20rem;"
class="mb-2"
>
<b-card-text>
<h1>{{item.name}}</h1>
<pre>{{item.description}}</pre>
</b-card-text>
<b-button :href="'/dashboard/'+item.name" variant="primary">More</b-button>
</b-card>
</b-col>
</b-row>
</b-container>
</div>
</template>
<script lang="js">
export default {
name: 'CardRenderer',
props: {
renderData: {
type: Array,
required: true,
default: () => ([]),
}
},
data() {
return {
rows: null
}
},
mounted() {
const itemsPerRow = 3
let rowss = []
// eslint-disable-next-line
console.log(this.renderData)
let arr = this.renderData
for (let i = 0; i < arr.length; i += itemsPerRow) {
let row = []
for (let z = 0; z < itemsPerRow; z++) {
row.push(arr[z])
}
rowss.push(row)
}
this.rows = rowss
// eslint-disable-next-line
// console.log(this.rows)
},
methods: {
},
computed: {
// rows() {
// }
}
}
</script>
<style scoped>
</style>
Something.vue
<template lang="html">
<!-- <h1>Something</h1> -->
<CardRenderer :renderData=valObj />
</template>
<script lang="js">
import CardRenderer from './CardRenderer'
export default {
name: 'something',
components: {
CardRenderer
},
props: [],
data() {
return {
valObj: []
}
},
mounted() {
let key = this.findUrl()
let value = this.$store.getters.responseAPI.apps.filter((elem) => {
if(elem.name == key) return elem.apps
})
if (value && value.length > 0)
this.valObj = value[0].apps
//eslint-disable-next-line
console.log(this.valObj)
},
methods: {
findUrl() {
let url = window.location.pathname.split("/").slice(-1)[0];
return url
}
},
computed: {
}
}
</script>
<style scoped >
.something {
}
</style>
This is what i am sending as a prop.
This is what i receive on the component
There's a couple of issues here.
First, you should be using kebab-cased attribute names and quotes around the value...
<CardRenderer :render-data="valObj" />
The second issue is timing related. In your component, you calculate rows based on the initial renderData in the mounted hook but this will not update when the parent component alters valObj.
What you should do instead is use a computed property which will react to valObj / renderData changes.
For example
data () { return {} }, // removed rows from data
computed: {
rows () {
let itemsPerRow = 3
let rows = []
for (let i = 0; i < this.renderData.length; i += itemsPerRow) {
rows.push(this.renderData.slice(i, i + itemsPerRow))
}
return rows
}
}

Vue.js - v-for indicies mixed up?

What do I have: components structure
<Games> // using v-for - iterate all games
--<Game> // using v-for - iterate all players
----<Player 1>
------<DeleteWithConfirmation>
----<Player 2>
------<DeleteWithConfirmation>
----<Player 3>
------<DeleteWithConfirmation>
----...
<DeleteWithConfirmation> implementation: two clicks are required for deleting game property.
<template>
<div>
<button #click="incrementDelete"
v-html="deleteButtonHTML"></button>
<button v-if="deleteCounter === 1" #click="stopDeleting">
<i class="undo icon"></i>
</button>
</div>
</template>
<script>
export default {
name: 'DeleteWithConfirmation',
data() {
return {
deleteCounter: 0
}
},
computed: {
deleteButtonHTML: function () {
if (this.deleteCounter === 0)
return '<i class="trash icon"></i>'
else
return 'Are you sure?'
}
},
methods: {
incrementDelete() {
this.deleteCounter++
if (this.deleteCounter === 2) {
//tell parent component that deleting is confirmed.
//Parent call AJAX than.
this.$emit('deletingConfirmed')
this.stopDeleting()
}
else if (this.deleteCounter > 2)
this.stopDeleting()
},
stopDeleting() {
Object.assign(this.$data, this.$options.data())
}
}
}
</script>
My problem: seems like indicies are mixed up:
Before deleting 4th player was on "Are you sure state" (deleteCounter === 1), but after deleting it went to initial state (deleteCounter === 0). Seems like 3rd component state haven't updated its deleteCounter, but its data (player's name was updated anyway).
After successfull deleting <Games> component data is fetched again.
You don't need a delete counter for achieving this. On the contrary, it makes it hard to understand your code. Just use a boolean like this:
<template>
<div>
<button #click="clickButton"
<template v-if="confirmation">
<i class="trash icon"></i>
</template>
<template v-else>
Are you sure?
</template>
</button>
<button v-if="confirmation" #click="confirmation = false">
<i class="undo icon"></i>
</button>
</div>
</template>
<script>
export default {
name: 'DeleteWithConfirmation',
data() {
return {
confirmation: false
}
},
methods: {
clickButton() {
if (!this.confirmation) {
this.confirmation = true;
} else {
this.$emit('deleting-confirmed');
}
}
}
</script>
The parent could then be looking e.g. like this:
<div class="row" v-if="showButton">
[...]
<delete-with-confirmation #deleting-confirmed="showButton = false">
</div>
One of the answers was deleted, I wish I could mention the initial author, but I don't remeber his username, so (changed a bit):
incrementDelete() {
if (this.deleteCounter === 1) { // 1 because there is "post-increment" at the end of the fucntion
this.deletingProgress = true
this.$emit('deletingConfirmed')
this.stopDeleting()
}
else if (this.deleteCounter > 1) // 1 because there is "post-increment" at the end of the fucntion
this.stopDeleting()
this.deleteCounter++ // "post-increment"
},
ssc-hrep3 answer is more clean (and lightweight) than mine approach, link.

setting :style from method

I have a little issue with setting element's width by using v-bind:style=...
The deal is that properties for style are requried faster, than I can provide them (in mounted). Any idea how to force update after I will fill my array with width's?
<template>
<div>
<div class="headings ">
<div class="t-cell head" v-for="(header, index) in headings"
:style="'min-width:'+ getHeight(index) +'px'"
>
{{header}}
</div>
</div>
</div>
<div class="fixed-table text-inline" >
<div class="t-cell head" v-for="(header, index) in headings" :ref="'head' + index">
{{header}}
</div>
</div>
</div>
</template>
<script>
export default {
mounted: function(){
this.getColumnWidths();
},
methods: {
getHeight(index){
return this.headerWidths[index];
},
getColumnWidths(){
const _that=this;
this.headings.forEach(function(element,index){
_that.headerWidths[index] = _that.$refs['head'+index][0].clientWidth
});
},
},
data: function () {
return {
headings: this.headersProp,
headerWidths:[],
}
}
}
</script>
It would be great if there would be some method to enforce update, as the width will probably change based on the content inserted.
Fiddle
https://jsfiddle.net/ydLzucbf/
You are being bitten by the array caveats. Instead of assigning individual array elements (using =), use vm.$set:
getColumnWidths() {
const _that = this;
this.header.forEach(function(element, index) {
_that.$set(_that.headerWidths, index, _that.$refs['head' + index][0].clientWidth)
});
console.log(this.headerWidths);
},