[Vuejs]-How to put a variable in the header section of a v-data-table from a JavaScript file?

-1👍

✅

You can access the properties of an object (imported or local) using two kinds of accessors: Dot notation and bracket notation. The below Mozilla doc explains them clearly.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors

Bracket notation provides more freedom when accessing properties inside an object.

Let’s say you have a Vue component’s with a language selector dropdown and a data-table.

Your data block looks like this:

data() {
    return {
        language: "en",
        languageOptions: ["en", "es"],
        headers: [
            { text: "Name", sortable: true, value: "name" },
            { text: "Lastname", sortable: true, value: "last_name" },
            { text: "Email", sortable: true, value: "email" },
            { text: "Role", sortable: true, value: "roles[0].name" },
            { text: "Actions", sortable: false, align: "center" }
        ],
    }
}

And for your messages.js file:

export default {
    en: {
        name: "Name",
        lastName: "Last Name",
        role: "Role",
        email: "Email",
        actions: "Actions"
    },
    es: {
        name: "Nombre",
        number: "Numero",
        role: "El Oficio"
        email: "Email",
        actions: "Acción"
    }
}

To replace the header texts with a value from the corresponding language option

messages[language][fieldName]:

Modified code:

data() {
    return {
        language: "en",
        languageOptions: ["en", "es"],
        headers: [
            { text: messages[language]["name"], sortable: true, value: "name" },
            { text: messages[language]["lastName"], sortable: true, value: "last_name" },
            { text: messages[language]["email"], sortable: true, value: "email" },
            { text: messages[language]["role"], sortable: true, value: "roles[0].name" },
            { text: messages[language]["actions"], sortable: false, align: "center" }
        ],
    }
}

I would also suggest checking out Vue’s localization plugin vue-i18n.

Leave a comment