VueJs Vuetify Click on table row event not reading item - vue.js

i am new to VueJs and Vuetify and i have a script that read data from a Json and display it into a Table.is a glossary type app. I have the option to select from different languages to be shown into the table. The problem is that when i click on a row i would like to display into a popup (alert) the item information. What i did is not working at all, is just showing the Alert popup but without information.
The format of the Json is:
{"glossary":[
{"id":2,"English":{"term":"contact","definition":"the state of physical touching"},"Vietnamese":{"term":"tiếp xúc"},"Simplified_Chinese":{"term":"接触"},"Arabic":{"term":"ملامسة"},"Swahili":{"term":"mgusano"}}]}
<v-data-table dense light :headers="selectedHeaders" :item-key="id" #click:row="showAlert(item)" :items="glossary.glossary" class="elevation-1" :single-expand="true" :disable-sort=true :search="search">
<template #item.ar.term="{item}">
<div style="text-align:right;">
<span>{{item.ar.term}}</span>
</div>
</template>
</v-data-table>
<script>
import About from '#/views/About.vue'
import json from '#/assets/data/glossary.json'
export default {
name: 'App',
components: { About },
data () {
return {
publicPath: process.env.BASE_URL,
glossary: json,
search: '',
value: [],
expanded: [],
selectedHeaders: [],
dialog: false,
headers: [
{ text: 'English', value: 'English.term' },
{ text: 'Vietnamese', value: 'Vietnamese.term' },
{ text: 'Arabic', value: 'Arabic.term' },
]
}
},
methods: {
filter(value, search, item) {
return value != null &&
search != null &&
typeof value === 'string' &&
value.toString().toLocaleLowerCase().indexOf(search.toLocaleLowerCase()) !== -1
},
showAlert(a){
if (event.target.classList.contains('btn__content')) return;
alert('Extra Information:! \n'+this.English.term );
console.log(this);
}
watch: {
value(val) {
this.selectedHeaders = val ;
}
},
created() {
this.selectedHeaders = this.headers;
}
}
</script>

You are not using a which is the item passed. this just returns the vue object. What you might want is this
showAlert(a){
if (a.target.classList.contains('btn__content')) return;
alert('Extra Information:! \n'+a.English.term );
console.log(a);
}
Here is a codepen that I found that should help you understand it better https://codepen.io/nsiggel/pen/KRdGgE. Note: I did not write this codepen.

Related

How do I work with Bootstrap select options when looping through a non-manual array?

I want to take an object containing an array that I get from a database, and I want the content of this array to appear as an select-option in a Bootstrap's form. I have tried reading Bootstrap's documentation on Form Select, as well as going through some old questions here.
In all cases I get examples of options that have been manually written into the code like this:
<script>
export default {
data() {
return {
selected: 'A',
options: [
{ item: 'A', name: 'Option A' },
{ item: 'B', name: 'Option B' },
{ item: 'D', name: 'Option C', notEnabled: true },
{ item: { d: 1 }, name: 'Option D' }
]
}
}
}
</script>
But this is not what I want. In my case I am fetching some data from a database and storing it in an object that contains an array. That array contains stuff like id, name etc. In my case I just want the name.
<template>
<b-container>
<b-form-select v-model="myDatabaseData">
</b-form-select>
</b-container>
</template>
<script>
export default {
data() {
return {
myDatabaseData: null,
options: []
};
},
created() {
myDB.getData()
.then(result => this.myDatabaseData = result.data)
.catch(error => console.error(error));
},
};
</script>
I have the v-model set up correctly, but what exactly do I do in options?
I thought this was the correct approach:
<template>
<b-container>
<b-form-select v-model="myDatabaseData" :options="options">
</b-form-select>
</b-container>
</template>
<script>
export default {
data() {
return {
myDatabaseData: null,
options: [{ value: this.myDatabaseData.name }]
};
},
created() {
myDB.getData()
.then(result => this.myDatabaseData = result.data)
.catch(error => console.error(error));
},
};
</script>

call child's computed method in VUE

I got three VUE components with a structure like this:
Table->Modal->Form. When user selects a record, the modal will be triggered and shown.
The Form component contains a computed method method1 for computing a property that is not stored by the database. I want to add a column in the Table component and display the return value of method1 for each record.
So something like this:
Vue.component('Form`, {
computed: {
method1: function() {
// ...some calculations
// No parameter cuz Form contains the selected record's data model
return a_calculated_value
}
}
}
And I want to call method1 on each of the records in Table
In addition, if possible I do not want to store this calculated value in the database.
Is this possible?
look at my example maybe it can help
<template>
<marker-table
ref="dt"
v-model="showTable"
:raw-table-data="tableData"
/>
<v-btn #click="showGasTable">
Show GAS Table
</v-btn>
<v-btn #click="shoeElecTable">
Show Electricity Table
</v-btn>
</template>
<script>
import markerTable from './components/markerTable.vue'
methods:{
showGasTable () {
this.tableData = this.gas
this.$refs.dt.popHeaders('gas')
},
showElecTable () {
this.tableData = this.elec
this.$refs.dt.popHeaders('electricity')
},
}
</script>
Component markerTable.vue
<template>
<v-data-table
:headers="headers"
:items="tableData"
>
</v-data-table>
</template>
<script>
export default { // eslint-disable-next-line
props: ['rawTableData'],
data () {
return {
headers: [],
title: '',
rawData: '',
tableData: ''
}
},
computed: {
dataUpdate () {
this.rawData = this.rawTableData
return this.rawData
}
},
methods: {
popHeaders (value) {
if (value === 'gas') {
this.headers =
[{ text: 'Volume', value: 'Vm' },
{ text: 'Day', value: 'day' }]
this.title = 'GAS Supply'
} else if (value === 'electricity') {
this.headers =
[{ text: 'Units', value: 'units' },
{ text: 'Watts', value: 'watt' },
{ text: 'Time', value: 'time' }]
this.title = 'Electric Supply'
}
}
}
You can access the method popHeader from the child component with sets of data and can process them in your child and it will be returned to your main page.

Vue.js: Child Component mutates state, parent displays property as undefined

I have a parent component that lists all the tasks:
<template>
<div class="tasks-wrapper">
<div class="tasks-header">
<h4>{{ $t('client.taskListingTitle') }}</h4>
<b-button variant="custom" #click="showAddTaskModal">{{ $t('client.addTask') }}</b-button>
</div>
<b-table
striped
hover
:items="tasks"
:fields="fields"
show-empty
:empty-text="$t('common.noResultsFound')">
</b-table>
<AddTaskModal />
</div>
</template>
<script>
import { mapActions, mapGetters } from 'vuex'
import AddTaskModal from '#/components/modals/AddTaskModal'
import moment from 'moment'
export default {
name: 'TaskListing',
components: {
AddTaskModal
},
data () {
return {
tasks: [],
fields: [
{ key: 'createdOn', label: this.$t('tasks.tableFields.date'), formatter: 'formatDate' },
{ key: 'domain', label: this.$t('tasks.tableFields.task') },
{ key: 'comment', label: this.$t('tasks.tableFields.comment') },
{ key: 'status', label: this.$t('tasks.tableFields.status') }
]
}
},
computed: {
...mapGetters('users', ['user'])
},
methods: {
...mapActions('tasks', ['fetchTasks']),
...mapActions('users', ['fetchUserById']),
formatDate: function (date) {
return moment.utc(date).local().format('DD.MM.YYYY HH:mm')
},
showAddTaskModal () {
this.$bvModal.show('addTaskModal')
}
},
async mounted () {
const currUserId = this.$router.history.current.params.id
if (this.user || this.user.userId !== currUserId) {
await this.fetchUserById(currUserId)
}
if (this.user.clientNumber !== null) {
const filters = { clientReferenceNumber: { value: this.user.clientNumber } }
this.tasks = await this.fetchTasks({ filters })
}
}
}
</script>
Inside this component there is a child which adds a task modal.
<template>
<b-modal
id="addTaskModal"
:title="$t('modals.addTask.title')"
hide-footer
#show="resetModal"
#hidden="resetModal"
>
<form ref="form" #submit.stop.prevent="handleSubmit">
<b-form-group
:invalid-feedback="$t('modals.requiredFields')">
<b-form-select
id="task-type-select"
:options="taskTypesOptions"
:state="taskTypeState"
v-model="taskType"
required
></b-form-select>
<b-form-textarea
id="add-task-input"
:placeholder="$t('modals.enterComment')"
rows="3"
max-rows="6"
v-model="comment"
:state="commentState"
required />
</b-form-group>
<b-button-group class="float-right">
<b-button variant="danger" #click="$bvModal.hide('addTaskModal')">{{ $t('common.cancel') }}</b-button>
<b-button #click="addTask">{{ $t('modals.addTask.sendMail') }}</b-button>
</b-button-group>
</form>
</b-modal>
</template>
<script>
import { mapActions, mapGetters } from 'vuex'
export default {
name: 'AddTaskModal',
data () {
return {
comment: '',
commentState: null,
taskTypesOptions: [
{ value: null, text: this.$t('modals.addTask.taskType') },
{ value: 'OnBoarding', text: 'Onboarding' },
{ value: 'Accounts', text: 'Accounts' },
{ value: 'TopUp', text: 'Topup' },
{ value: 'Overdraft', text: 'Overdraft' },
{ value: 'Aml', text: 'Aml' },
{ value: 'Transfers', text: 'Transfers' },
{ value: 'Consultation', text: 'Consultation' },
{ value: 'TechnicalSupport', text: 'TechnicalSupport' },
{ value: 'UnblockPin', text: 'UnblockPin' },
{ value: 'Other', text: 'Other' }
],
taskType: null,
taskTypeState: null
}
},
computed: {
...mapGetters('users', ['user']),
...mapGetters('tasks', ['tasks'])
},
methods: {
...mapActions('tasks', ['addNewTask', 'fetchTasks']),
...mapActions('users', ['fetchUserById']),
async addTask (bvModalEvt) {
bvModalEvt.preventDefault()
if (!this.checkFormValidity()) { return }
const currUserId = this.$router.history.current.params.id
if (this.user || this.user.userId !== currUserId) {
await this.fetchUserById(currUserId)
}
const data = {
clientPhone: this.user.phoneNumber,
comment: this.comment,
clientReferenceNumber: this.user.clientNumber,
domain: this.taskType
}
await this.addNewTask(data)
if (this.user.clientNumber !== null) {
const filters = { clientReferenceNumber: { value: this.user.clientNumber } }
this.tasks = await this.fetchTasks({ filters })
// this.tasks may be useless here
}
console.log(this.tasks)
this.$nextTick(() => { this.$bvModal.hide('addTaskModal') })
},
checkFormValidity () {
const valid = this.$refs.form.checkValidity()
this.commentState = valid
this.taskTypeState = valid
return valid
},
resetModal () {
this.comment = ''
this.commentState = null
this.taskTypeState = null
}
}
}
</script>
When I add a task I call getalltasks to mutate the store so all the tasks are added. Then I want to render them. They are rendered but the property createdOn on the last task is InvalidDate and when I console log it is undefined.
The reason I need to call gettasks again in the modal is that the response on adding a task does not return the property createdOn. I do not want to set it on the front-end, I want to get it from the database.
I logged the store and all the tasks are added to the store.
Why is my parent component not rendering this particular createdOn property?
If I refresh the page everything is rendering fine.
If you add anything into a list of items that are displayed by v-for, you have to set a unique key. Based on your explanation, I assume that your key is the index and when you add a new item, you mess with the current indexes. Keys must be unique and unmutateable. What you need to do is to create a unique id for each element.
{
id: Math.floor(Math.random() * 10000000)
}
When you create a new task, use the same code to generate a new id, and use id as key. If this doesn't help, share your d-table and related vuex code too.

How to generate dynamic data table through api call in vuetify in vuejs

I am trying to generate dynamic data table through Vuetify ,in vuejs but dont see any example in vuetify official documentation,does anyone mind sharing an example
By "dynamic" I'm guessing you mean data loads asynchronously from an API. The Vuetify docs have numerous examples of data tables including one that simulates requesting data from an API. A very basic implementation looks something like (note: this example uses the random user generator API:
<template>
<v-data-table
:headers="headers"
:items="people"
item-key="login.uuid"
:loading="loading"
:options.sync="options"
:server-items-length="totalPeople"
#pagination="updatePage"
#update:options="customSort"
></v-data-table>
</template>
<script>
import axios from 'axios'
export default {
data: () => ({
apiURL: 'https://randomuser.me/api/',
headers: [
{ text: 'Name', value: 'name', align: 'start' },
{ text: 'Country', value: 'country' },
{ text: 'DOB (Age)', value: 'dob' },
{ text: 'Contacts', value: 'contacts' },
],
loading: false,
options: {
page: 1,
itemsPerPage: 10,
sortBy: ['name'],
sortDesc: [true],
},
people: [],
}),
mounted () {
this.getPeople()
},
methods: {
async getPeople (page = 1, results = 10, seed = 'example') {
this.loading = true
const params = { params: { page, results, seed } }
try {
this.people = (await axios.get(this.apiURL, params)).data.results
this.loading = false
} catch (error) {
console.log(error)
this.loading = false
}
},
updatePage (pagination) {
const { itemsPerPage: results, page } = pagination
this.pagination = pagination
this.getPeople({ page, results })
},
customSort (options) {
// The Random User API does NOT support sorting, but if it did, you
// would need to make an API call that returned a sorted
// list of results based on the sort parameter(s)
console.log(options)
},
},
}
</script>
For a more complex example that uses more of Vuetify's features, check out this codepen.

vue-table-2 with Vuex - not able to change the count property

I'm using the vue-table-2 component : https://github.com/matfish2/vue-tables-2 and I'm struggling to make it work as I want.
I have an API (using API Platform) which is already making all the pagination works. So when I fetch for the first time my list of companies it gives the first ten results + the total rows. I store all of this in my vuex store and I am able to display the list in my table (with useVuex false or true so I don't really understand how this parameter works). The issue is I cannot paginate because I only got ten results and can't get the total rows count to change so I do not get the pagination element at the bottom and can't bind something to it to fetch the other pages later.
Since I'm pretty new to VueJs I can't figure out how this should work with my API. Here is my code so far:
My DataTable element :
<v-client-table name="company" :columns="columns" :data="companies" :options="options" :theme="theme" id="dataTable">
<b-button slot="actions" slot-scope="props" variant="secondary" size="sm" class="btn-pill">Edit</b-button>
</v-client-table>
And my script :
<script>
import Vue from 'vue'
import { ClientTable, Event } from 'vue-tables-2'
import { mapGetters } from 'vuex'
Vue.use(ClientTable)
export default {
name: 'DataTable',
components: {
ClientTable,
Event,
},
data: function() {
return {
columns: ['name', 'actions'],
options: {
headings: {
name: 'Name',
actions: 'Actions',
},
sortable: ['name'],
filterable: ['name'],
sortIcon: {
base: 'fa',
up: 'fa-sort-asc',
down: 'fa-sort-desc',
is: 'fa-sort',
},
pagination: {
chunk: 5,
edge: false,
nav: 'scroll',
},
},
useVuex: true,
theme: 'bootstrap4',
template: 'default',
}
},
computed: {
...mapGetters({
companies: 'companyModule/companies',
totalCompanies: 'companyModule/totalCompanies',
}),
},
}
</script>
This is in my component loading the data where I specify how many items per page I want my api to send me and the page I want:
created() {
this.$store.dispatch('companyModule/FETCH_COMPANIES', {
page: 1,
nbItemPerPage: 10,
})
},
My store looks like this:
import ApiService from '#/services/APIService'
export const companyModule = {
strict: true,
namespaced: true,
state: {
companies: [],
totalCompanies: 0,
},
getters: {
companies: state => state.companies,
totalCompanies: state => state.totalCompanies,
},
mutations: {
SET_COMPANIES(state, data) {
state.companies = data.companies
state.totalCompanies = data.totalCompanies
},
},
actions: {
FETCH_COMPANIES(context, payload) {
payload.entity = 'companies'
return ApiService.get(payload).then(data => {
context.commit('SET_COMPANIES', data)
})
},
},
}
When I received my data, I stored everything in my companies state and for now I'm storing everything I'm getting from my API and this looks like this :
{
"#id": "/api/admin/companies/1",
"#type": "Company",
"id": 1,
"name": "Test Company",
}
Thanks in advance for your help !
watch: {
'companies': {
handler (newValue, oldValue) {
this.totalRows=this.companies.length;
},
deep: true
}
},
Vue “watch” is a powerful reactive option attribute to the vue framework that helps front-end developers listen to changes made on a value and then react to it.
So, once the totalRows is set, you can assign it to the table attributes and the table will change accordingly.
For my case, I used it for bootstrap table as follows:
<b-pagination
:total-rows="totalRows"
:per-page="perPage"
></b-pagination>