How to convert table headings in Bootstrap-Vue.js

For a few nights now, I've been struggling to translate the table header in my vue.js component. It seems like I'm missing something as I'm new to Vue.js and can't seem to figure out what's wrong. Translating within the HTML works perfectly fine, but when I attempt to translate attributes within the script tag (such as data attributes), I encounter console errors stating that certain fields cannot be found.

Here's what I've done: I initialized the i18n component in the main.js file.

import Vue from 'vue'
import BootstrapVue from 'bootstrap-vue'
import App from './App'
import router from './router'
import axios from './api'
import VueAxios from 'vue-axios'
import VueI18n from 'vue-i18n'

Vue.use(BootstrapVue)
Vue.use(VueAxios, axios)
Vue.prototype.$axios = axios;

Vue.use(VueI18n)

// Ready translated locale messages
const messages = {
    en: require('./locales/en_GB.json'),
    nl: require('./locales/nl_NL.json')
}

  // Create VueI18n instance with options
  const i18n = new VueI18n({
    locale: 'nl', // set locale
    fallbackLocale: 'en',
    messages // set locale messages
  })

// TODO load messages async, otherwise all messages will be loaded at once: http://kazupon.github.io/vue-i18n/guide/lazy-loading.html

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  i18n,
  template: '<App/>',
  components: {
    App
  }
})

Then, within the script tag of the Users component, I'm trying to translate the table header. However, I keep getting console errors like TypeError: "o is undefined".

  data: () => {
    return {
      items_data: [],
      fields: [
        {key: this.$i18n.t('next')}, //<-- Translate table header values
        {key: 'name'},
        {key: 'registered'},
        {key: 'role'},
        {key: 'status'}
      ],
      currentPage: 1,
      perPage: 5,
      totalRows: 0
    }

You can view the full file below:

<template>
  <b-row>
    <b-col cols="12" xl="6">
      <transition name="slide">
      <b-card :header="caption">
        <b-table :hover="hover" :striped="striped" :bordered="bordered" :small="small" :fixed="fixed" responsive="sm" :items="items" :fields="fields" :current-page="currentPage" :per-page="perPage" @row-clicked="rowClicked">
          <template slot="id" slot-scope="data">
            <strong>{{data.item.id}}</strong>
          </template>
          <template slot="name" slot-scope="data">
            <strong>{{data.item.name}}</strong>
          </template>
          <template slot="status" slot-scope="data">
            <b-badge :variant="getBadge(data.item.status)">{{data.item.status}}</b-badge>
          </template>
        </b-table>
        <nav>
          <b-pagination size="sm" :total-rows="5" :per-page="perPage" v-model="currentPage" :prev-text="$t('previous')" :next-text="$t('next')" hide-goto-end-buttons/>
        </nav>
      </b-card>
      </transition>
    </b-col>
  </b-row>
</template>

<script>
var usersData = null;
export default {

  name: 'Test Users',
  props: {
    caption: {
      type: String,
      default: 'Users 2'
    },
    hover: {
      type: Boolean,
      default: true
    },
    striped: {
      type: Boolean,
      default: true
    },
    bordered: {
      type: Boolean,
      default: false
    },
    small: {
      type: Boolean,
      default: false
    },
    fixed: {
      type: Boolean,
      default: false
    }
  },
  data: () => {
    return {
      items_data: [],
      fields: [
        {key: this.$i18n.t('next')}, //<-- Translate table header values
        {key: 'name'},
        {key: 'registered'},
        {key: 'role'},
        {key: 'status'}
      ],
      currentPage: 1,
      perPage: 5,
      totalRows: 0
    }
  },
  mounted() {
    this.axios.getAll()
      .then(response => {
        //this.$log.debug("Data loaded: ", response.data) 
        this.items_data = response.data
      }).catch(error => {  
      //this.$log.debug(error)  
      this.error = "Failed to load todos"  
    }) 
  },
  computed: {
    items: function () { 
      return this.items_data;
    }
  },
  methods: {
    getBadge(status) {
      return status === 'Active' ? 'success'
        : status === 'Inactive' ? 'secondary'
          : status === 'Pending' ? 'warning'
            : status === 'Banned' ? 'danger' : 'primary'
    },
    getRowCount(items) {
      return items.length
    },
    userLink(id) {
      return `users/${id.toString()}`
    },
    rowClicked(item) {
      const userLink = this.userLink(item.id)
      this.$router.push({path: userLink})
    }

  }
}
</script>

<style scoped>
.card-body >>> table > tbody > tr > td {
  cursor: pointer;
}
</style>

I would greatly appreciate any help or guidance on how to properly translate these types of texts. Google hasn't provided a definitive answer, so any assistance would be invaluable.

Answer №1

As stated in the official documentation:

The fields prop is essential for customizing table column headings and determining the order in which data columns are displayed. The keys within the field object are crucial for extracting values from each item row...

This implies that the value of keys in your fields property should correspond to the keys in your items. For instance, first_name:

fields: [
  { key: 'first_name'}
],
items: [
  { first_name: 'John' },
  { first_name: 'Jane' }
]

If you wish to personalize your headers with translated titles, you can utilize label:

fields: {
  {
    next: { label: this.$i18n.t('next') },
    name: { label: this.$i18n.t('name') },
    registered: { label: this.$i18n.t('registered') },
    role: { label: this.$i18n.t('role') },
    status: { label: this.$i18n.t('status') }
  }
}

Answer №2

var dataUsers = null;
import localization from 'your-path/localization';
export default {

  name: 'Test Users',
  props: {
    caption: {
      type: String,
      default: 'Users 2'
    },
    hover: {
      type: Boolean,
      default: true
    },
    striped: {
      type: Boolean,
      default: true
    },
    bordered: {
      type: Boolean,
      default: false
    },
    small: {
      type: Boolean,
      default: false
    },
    fixed: {
      type: Boolean,
      default: false
    }
  },
  data: () => {
    return {
      info_data: [],
      fields: [
        {key: localization.t('next')}, //<-- Add Like this, you need to recreate your component
        {key: 'name'},
        {key: 'registered'},
        {key: 'role'},
        {key: 'status'}
      ],
      currentPage: 1,
      perPage: 5,
      totalRows: 0
    }
  },
  mounted() {
    this.fetch.getAll()
      .then(response => {
        //this.$log.debug("Data loaded: ", response.data) 
        this.info_data = response.data
      }).catch(error => {  
      //this.$log.debug(error)  
      this.error = "Failed to load todos"  
    }) 
  },
  computed: {
    items: function () { 
      return this.info_data;
    }
  },
  methods: {
    getStatusBadge (status) {
      return status === 'Active' ? 'success'
        : status === 'Inactive' ? 'secondary'
          : status === 'Pending' ? 'warning'
            : status === 'Banned' ? 'danger' : 'primary'
    },
    getTotalRowCount (items) {
      return items.length
    },
    userRedirectLink (id) {
      return `users/${id.toString()}`
    },
    rowSelect (item) {
      const userDataLink = this.userRedirectLink(item.id)
      this.$router.push({path: userDataLink})
    }

  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<template>
  <b-row>
    <b-col cols="12" xl="6">
      <transition name="slide">
      <b-card :header="caption">
        <b-table :hover="hover" :striped="striped" :bordered="bordered" :small="small" :fixed="fixed" responsive="sm" :items="items" :fields="fields" :current-page="currentPage" :per-page="perPage" @row-clicked="rowSelect">
          <template slot="id" slot-scope="data">
            <strong>{{data.item.id}}</strong>
          </template>
          <template slot="name" slot-scope="data">
            <strong>{{data.item.name}}</strong>
          </template>
          <template slot="status" slot-scope="data">
            <b-badge :variant="getStatusBadge(data.item.status)">{{data.item.status}}</b-badge>
          </template>
        </b-table>
        <nav>
          <b-pagination size="sm" :total-rows="5" :per-page="perPage" v-model="currentPage" :prev-text="$t('previous')" :next-text="$t('next')" hide-goto-end-buttons/>
        </nav>
      </b-card>
      </transition>
    </b-col>
  </b-row>
</template>

Answer №3

Utilize the Computed Property to Enhance Efficiency:

    input code here
<b-table :fields="fields" />

...

methods: {
  translateCol (colName) {
    return this.$i18n.t('.fields.' + colName + '.label')
  }
},
computed: {
  fields () {
    return [
      { key: 'id', label: this.translateCol('id'), sortable: true },
      { key: 'name', label: this.translateCol('name'), sortable: true },
      { key: 'description', label: this.translateCol('description'), sortable: true },

    ]
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues persist with jQuery ajax request attempting to retrieve data from database

I attempted to retrieve data from my database using jQuery AJAX. Below is the code snippet I used: <script> $(document).ready(function(){ function fetch_data(){ $.ajax({ type:"POST", url:"http://localhost:88/phpPoint/select.php", success:function(re ...

Whenever the selected option in an HTML dropdown menu is modified, a corresponding input field should be automatically adjusted

Within my Rails application, I am facing a challenge related to updating the value of a text_field when a user chooses a different option from a select tag. The select tag is populated from a model which contains a list of countries for users to choose fro ...

Navigating Through Secondary Navigation with Ease

In my React project, I am developing a mega-menu styled dropdown navigation. As a functional component, I am utilizing the useState hook to manage the state and control the display of sub-navigation items. The functionality of the dropdown is operational, ...

jQuery form validation issue, unresponsive behavior

<!DOCTYPE html> <html> <head> <title> jquery validation </title> </head> <body> <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js" type="text/javascript"> ...

What could be causing this function to work in Google Chrome, but not in Firefox?

For some reason, in Firefox, this section of the code never returns true. However, it works perfectly fine in Google Chrome. if(restrictCharacters(this, event, digitsOnly)==true) The expected behavior is that if a user inputs a number from 1 to 5 in the ...

Performance of obtaining image data

Is anyone else experiencing a significant lag when trying to retrieve the state of a single pixel on the canvas? Take a look at my JS code below: var state = ctx.getImageData(x,y,1,1).data; state = 'rgba(' + state[0] + ',' + state[1] ...

How can I effectively refresh the provider_token / access token for Discord in NextJS with Supabase Auth?

Currently, I have encountered an issue with my NextJs project using Supabase Auth for authentication. I am currently utilizing the Discord provider and everything works fine initially. However, after a few minutes, the session object gets updated and the p ...

When using a Vue.js component, the value of this.$route can sometimes come back

I am attempting to retrieve the parameters from the URL and pass them into a method within a Vue component. Despite following advice to use this.$route, I am consistently getting an 'undefined' response. I have tried various solutions suggested ...

Error encountered during the execution of the store method in Ajax CRUD operation

Greetings, I'm encountering an error in my AJAX code every time I try to execute the store function Below is my controller: public function store_batch(Request $request) { $rules = array( 'batch_name'=>'required:max:20| ...

"Validation with Express-validator now includes checking the field in cookies instead of the request

My current validator is set up like this: const validationSchema = checkSchema({ 'applicant.name': { exists: true, errorMessage: 'Name field is required', }, }); and at the beginning of this route (the rest is not relevant) ...

Create a hover effect on HTML map area using CSS

Is it possible to change the background color of an image map area on hover and click without using any third-party plugins? I attempted the following code: $(document).on('click', '.states', function(){ $(this).css("backgro ...

Validating forms using Ajax, Jquery, and PHP, with a focus on addressing

I am currently working on processing a form using AJAX, jQuery, and PHP. However, I have encountered a 404 error while doing so. I tried searching for a solution before posting here but unfortunately couldn't find one. Below is the content of my .js f ...

"A currency must be designated if there is a value present in a monetary field" - The default currency is established

I've encountered a major issue with one of my managed solutions. I have a customized workflow that generates multiple custom entities, each with various money fields. Here's the scenario when I trigger my workflow: The custom workflow enters a ...

elimination of nonexistent object

How can I prevent releasing data if two attributes are empty? const fork = [ { from: 'client', msg: null, for: null }, { from: 'client', msg: '2222222222222', for: null }, { from: 'server', msg: 'wqqqqqqqq ...

Dividing the text by its position value and adding it to a fresh object

I needed to divide the paragraph into sections based on its entityRanges. Here is what the original paragraph looks like: { type: 'paragraph', depth: 1, text: 'Do you have questions or comments and do you wish to contact ABC? P ...

I'm encountering an issue with my array in JavaScript while using // @ts-check in VS Code. Why am I receiving an error stating that property 'find' does not exist on my array? (typescript 2.7

** update console.log(Array.isArray(primaryNumberFemales)); // true and I export it with: export { primaryNumberFemales, }; ** end update I possess an array (which is indeed a type of object) that is structured in the following manner: const primar ...

Switch from buffer to base64 encoding for viewing in Angular

Hello, I have developed an application using the MEAN stack. Currently, I am facing an issue with retrieving images from my endpoint. The image array values that I am receiving look like this: 8,8,7,7,9,8,9,8,9,8,9,9,8,8,8,8,7,9,7,7,9,10,16,13,8,8,16,9,7, ...

How can I send extra information along with my Ajax request in jQuery UI Autocomplete?

I currently have two jQuery UI Autocomplete widgets set up. The first autocomplete allows the user to enter a client's name, narrowing down options until the correct client is selected. A callback function then takes the ID of the chosen client and st ...

Creating custom CSS for Styled Components in ReactJS

I'm struggling with CSS in React using styled components. Below is the code snippet I am working with: import React from 'react'; import { Navbar, Container, Row, Col } from 'reactstrap'; import styled from 'styled-components& ...

Download a complete website using PHP or HTML and save it for offline access

Is there a way to create a website with a textbox and save button, where entering a link saves the entire website like the 'save page' feature in Google Chrome? Can this be done using PHP or HTML? And is it possible to zip the site before downloa ...