The Vue i18n-$t is not defined beyond the template

Hey there, when I use {{$t('dash.port')}} within a template, the translation works perfectly. Now, I have an antdv table with columns declared as follows:

const columns = [
  {
    title:"pone",
    dataIndex: 'pone',
    key: 'pone',
  },
    ...
    ]

//Here's the antdv table component :

    <template>
 <a-table :data-source="data" :columns="columns">
  <template #filterDropdown="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }">
  <div style="padding: 8px">
    <a-input
      ref="searchInput"
      :placeholder="`Search ${column.dataIndex}`"
      :value="selectedKeys[0]"
      style="width: 188px; margin-bottom: 8px; display: block"
      @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
      @pressEnter="handleSearch(selectedKeys, confirm, column.dataIndex)"
    />
    <a-button
      type="primary"
      size="small"
      style="width: 90px; margin-right: 8px"
      @click="handleSearch(selectedKeys, confirm, column.dataIndex)"
    >
      <template #icon><SearchOutlined /></template>
      Search
    </a-button>
    <a-button size="small" style="width: 90px" @click="handleReset(clearFilters)">
      Reset
    </a-button>
  </div>
</template>
<template #filterIcon="filtered">
  <search-outlined :style="{ color: filtered ? '#108ee9' : undefined }" />
</template>
<template #customRender="{ text, column }">
  <span v-if="searchText && searchedColumn === column.dataIndex">
    <template
      v-for="(fragment, i) in text
        .toString()
        .split(new RegExp(`(?<=${searchText})|(?=${searchText})`, 'i'))"
    >
      <mark
        v-if="fragment.toLowerCase() === searchText.toLowerCase()"
        class="highlight"
        :key="i"
      >
        {{ fragment }}
      </mark>
      <template v-else>{{ fragment }}</template>
    </template>
  </span>
  <template v-else>
    {{ text }}
  </template>
</template>
</a-table>
//script part where $t is not working
<script>
 import { SearchOutlined } from '@ant-design/icons-vue';
 import { defineComponent, reactive, ref } from 'vue';
    const data = [
     {
       key: '1',
       name: 'John Brown',
        age: 32,
       address: 'New York No. 1 Lake Park',
      },
    ..
   ];
   export default defineComponent({
    components: {
     SearchOutlined,
   },

 setup() {
const state = reactive({
  searchText: '',
  searchedColumn: '',
});
const searchInput = ref();
const columns = [
  {
    title: 'pone',
    dataIndex: 'pone',
    key: 'pone',
    slots: {
      filterDropdown: 'filterDropdown',
      filterIcon: 'filterIcon',
      customRender: 'customRender',
    },
    onFilter: (value, record) =>
      record.pone.toString().toLowerCase().includes(value.toLowerCase()),
    onFilterDropdownVisibleChange: visible => {
      if (visible) {
        setTimeout(() => {
          console.log(searchInput.value);
          searchInput.value.focus();
        }, 0);
      }
    },
  },
  ....
];

const handleSearch = (selectedKeys, confirm, dataIndex) => {
  confirm();
  state.searchText = selectedKeys[0];
  state.searchedColumn = dataIndex;
};

const handleReset = clearFilters => {
  clearFilters();
  state.searchText = '';
};

return {
  data,
  columns,
  handleSearch,
  handleReset,
  searchText: '',
  searchInput,
  searchedColumn: '',
  };
  },
  });
   </script>

I'm trying to change the title using $t but when I do

title:"$t('dash.pone')",
I get an error saying $t is not defined. How can I resolve this issue?

Answer №1

I haven't had the chance to explore vue3 yet so I'm not familiar with how it functions, but you may want to check out all the examples provided here: https://github.com/intlify/vue-i18n-next/tree/master/examples/composition

However, there's a possibility that this specific example could be useful:

const app = createApp({
  setup() {
    const { t, locale } = useI18n()

    t('dash.port') // maybe this one works?

    return { t, locale }
  }
})

Answer №2

Oh, interesting! It looks like you've embraced the new Vue3 composition API. While vue-i18n is a bit behind, there's a repository for the upcoming version 9. Simply upgrade the package and follow the migration instructions, then implement your translations in setup functions just like this:

import { defineComponent, reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
 
setup() {
  const { tm } = useI18n();

  const columns = [
    {
      title: tm('dash.pone'),
      dataIndex: 'pone',
      key: 'pone',
      // ...
    },
  ];
];

Answer №3

Encountering a similar problem with vue3 and the composition API, I was able to resolve it using this method:

Firstly, import i18n (ensuring the correct path is provided):

import i18n from '@/plugins/i18n'

Then, to access the $t function:

i18n.global.t("WordToTranslate")

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

Discovering the geographical location of all users using Node.js: A step-by-step guide

My current task involves determining the geoip location of users. I have implemented a code that stores the user's address in the database and then displays the geoip location accordingly. However, if a user changes their location and logs in from a d ...

What's the best way to arrange the layout to ensure that every row contains exactly three items that are evenly spaced apart?

Struggling to figure out how to display three items in each row with even spacing using react js and bootstrap. I've been grappling with this for hours today, trying to implement grid layouts on the page. I managed to render 3-4 items on each row, bu ...

What is the method to trigger a function upon opening an anchor tag?

When a user opens a link in my React app, I need to send a post request with a payload to my server. My current strategy involves using the onClick and onAuxClick callbacks to handle the link click event. However, I have to filter out right-clicks because ...

What are the steps to customize the $http interface in AngularJS?

Within my application, I am making an $http call with the following code: $http({ url: '/abc' method: "PUT", ignoreLoadingBar: true }) This $http call includes a custom par ...

Changing <br/> tag to (new line) using jQuery

I attempted to use the following code snippet in jQuery to replace the <br/> tag with "\n" (new line), but unfortunately it did not yield the desired result: $("#UserTextArea").html(data.projectDescription).replace(/\<br\>/g ...

Switch the background color of a list item according to a JSON search

Our organization is in need of a feature where members can be inputted into a field and the background color of the parent list item changes based on the name lookup in a JSON file. We are open to a jQuery solution, but JavaScript will also work! You can ...

Find the average value of an array containing objects

Imagine I have an array of objects like this: const BookDetails = [ { bookName: 'Harry Pottar', readingTime: 10663 }, { bookName: 'Harry Pottar', readingTime: 10986 }, { bookName: 'kaptura Tech', readingTime: 7034 } ] I ...

Implementing snow animation exclusively to a targeted div

I found some helpful code at and now I'm facing an issue where the snow effect is falling all over my page instead of just within the banner div... // Storing Snowflake objects in an array var snowflakes = []; // Browser window size variables v ...

The variable that was posted in the JavaScript 'if' statement seemed to vanish in an instant

My website has forms that send data to a PHP file, triggering the appearance of items in a cart: <form method="post"><fieldset> <input type="hidden" name="jcartToken" value="<?php echo $_SESSION['jcartToken'];?>" /> <i ...

"Let's delve into the world of dynamic variables and Javascript once

As a newcomer to JS, I've scoured countless posts for solutions, but nothing seems to work for me. The issue arises when trying to abstract the code to handle all variables rather than just explicitly expressed values. I am open to alternative method ...

Utilize Vue.js to easily upload images alongside form input fields

I have recently started a small project with Vue Js. I am trying to incorporate an upload file option in my contact form. Due to the numerous input text fields, I am using serialize for the form. However, I am facing issues with the append function. How ca ...

Tips for simulating mouse events in Jasmine tests for Angular 2 or 4

New to Jasmine testing, I'm exploring how to test a directive that handles mouse events such as mouse down, up, and move. My main query is regarding passing mouse coordinates from the Jasmine spec to my directive in order to simulate the mouse events ...

Incorporate JSON data into an existing array within Angular that already contains JSON data

I have a problem with adding new jsonp data to an existing array while loading more content near the bottom of the page. Instead of appending the new data, it replaces what's already there. function AppCtrl($scope, Portfolio, $log, $timeout, $ionicSl ...

What is the best way to set wrapper props without hiding it from showing up in attrs?

Creating a Wrapper Component with Specific Props <script setup lang="ts"> import InputBase,{ Props as InputBaseProps } from "./InputBase.vue"; interface Props extends InputBaseProps { label?: string; labelClassName?: string; ...

Properly storing information in the mongoDB

Having trouble saving data in my Angular application correctly. Here is a snippet of my API code: .post('/type/add', function(req, res){ var type = new NewType({ type: req.body.type, subtype: req.body.subtype, }); type.save ...

Using Vue, the placeholder attribute can be set for a base input label

Looking for some assistance with debugging this issue. I have two components, BaseInput and BaseTextarea. For the input and textarea elements, I am adding the placeholder attribute as needed. All other attributes are being added to the label element. Wh ...

Exploring Globalization in NextJS

As I work on setting up a NextJS project that requires i18n support, I have come across various libraries dedicated to internationalization. Are these libraries truly necessary? After reviewing the documentation, I find the idea of keeping an object at a g ...

Creating an AJAX request in PHP to send data from multiple input fields with the same name

My goal is to create a poll system similar to Facebook for my project, but I am facing a challenge. I have implemented the following JavaScript code to add answers to inputs: $("body").on("click",".createnew", function(){ $(".inputsl").append("<d ...

Tips for preventing repetition in http subscribe blocks across various components

Imagine a scenario where there is a service used for making HTTP request calls. There are two different components (which could be more than two) that need to send the same request using the same observables via this service. After receiving the result, it ...

How come my uploaded Excel Javascript add-on opens in an external browser instead of the task pane?

Note: It has come to my attention that I must save the taskpane.html file on my local drive before it opens in an external browser. This detail slipped my notice last week. I am currently developing a Javascript, or rather Typescript, API add-in for Excel ...