Vue Setup Function

Posted on  by admin
Modified2 years, 1 month ago. I have a function that helps filter data. I am using v-on:change when a user changes the selection but I also need the function to be called even before the user selects the data.

This is my function:. In the blade file I use blade forms to perform the filters:. This works fine when I select a specific item. Then if I click on all lets say all floors, it works.

What I need is when the page is loaded, it calls the getUnits method which will perform the $http.post with empty input. In the backend I have handled the request in a way that if the input is empty it will give all the data.

How can I do this in vuejs2? My Code: http://jsfiddle.net/q83bnLrx. 33 gold badges1818 silver badges3838 bronze badges.

3838 bronze badges. You can call this function in beforeMount section of a Vue component: like following:.

  • Working fiddle: https://jsfiddle.net/q83bnLrx/1/.
  • There are different lifecycle hooks Vue provide:.
  • I have listed few are :.
  • beforeCreate: Called synchronously after the instance has just been initialized, before data observation and event/watcher setup.
  • created: Called synchronously after the instance is created.
  • At this stage, the instance has finished processing the options which means the following have been set up: data observation, computed properties, methods, watch/event callbacks.
  • However, the mounting phase has not been started, and the $el property will not be available yet.
  • beforeMount: Called right before the mounting begins: the render function is about to be called for the first time.
  • mounted: Called after the instance has just been mounted where el is replaced by the newly created vm.$el.

beforeUpdate: Called when the data changes, before the virtual DOM is re-rendered and patched.

updated: Called after a data change causes the virtual DOM to be re-rendered and patched.

  • You can have a look at complete list here.
  • You can choose which hook is most suitable to you and hook it to call you function like the sample code provided above.
  • 3636 gold badges175175 silver badges230230 bronze badges.
  • 230230 bronze badges. If you get data in array you can do like below.
  • It's worked for me.

Initial Setup of the Vue.js App

136136 bronze badges. you can also do this using mounted. 11 gold badge2121 silver badges4141 bronze badges.

4141 bronze badges. Beware that when the mounted event is fired on a component, not all Vue components are replaced yet, so the DOM may not be final yet.

To really simulate the DOM onload event, i.e. to fire after the DOM is ready but before the page is drawn, use vm.$nextTick from inside mounted:.

2121 gold badges174174 silver badges237237 bronze badges. 237237 bronze badges.

You need to do something like this (If you want to call the method on page load):.

  • 2626 gold badges279279 silver badges299299 bronze badges.
  • 299299 bronze badges. Modified28 days ago. How to create Event Bus in Vue 3? In Vue 2, it was:.
  • In Vue 3, Vue is not a constructor anymore, and Vue.createApp({}); returns an object that has no $on and $emit methods.
  • 129129 bronze badges. 1,72422 gold badges99 silver badges1919 bronze badges.

99 silver badges1919 bronze badges. As suggested in official docs you could use mitt library to dispatch events between components, let suppose that we have a sidebar and header which contains a button that close/open the sidebar and we need that button to toggle some property inside the sidebar component :.

  1. in main.js import that library and create an instance of that emitter and define as a global property:. in header emit the toggle-sidebar event with some payload :.
  2. In sidebar receive the event with the payload:. For those using composition api they could use emitter as follows :.
  3. Create a file src/composables/useEmitter.js. And from there on you can use useEmitter just like you would with useRouter:.
  4. 1414 gold badges105105 silver badges129129 bronze badges. 129129 bronze badges.
  5. On version 3 of Vue.js, you can use either a third-party library, or use the functionality written in the publisher-subscriber(PubSub concept) programming pattern.

Content of EventBus class file:. usage in project, emit event:.

Setting Up Lokalise

Alexander SimonovAlexander Simonov. With Vue composition and defineEmit you can even make it easier :.

I just showed it with one children, but you could pass though the emit function down to other children.

Benjamin FourgeaudBenjamin Fourgeaud.

  • Grab your free trial (no credit card is required).
  • Proceed to Personal profile > API tokens.
  • Generate a new read-write token (make sure to keep it safe).
  • Download CLIv2 and unpack it somewhere on your PC.
  • cd into the created directory
  • Create a new Lokalise project by running lokalise2 project create --name VueJS --token YOUR_TOKEN_HERE --languages "[{\"lang_iso\":\"ru\"},{\"lang_iso\":\"en\"}]" --base-lang-iso "en". Adjust the supported languages as necessary.
  • The above command is going to return an object with the project details. Copy the project_id as we will need it later.

The basic setup is done, and we can proceed to the next part!

Performing Simple Translations

Storing Vue Translations in JSON Files

To get started with Vue I18n, let’s see how to perform basic translations. For instance, we may want to greet our users on the main page of the site. To achieve that, add English translation to locales/en.json:

There are a few things to note here:

  • Your translations are stored in simple JSON files. The key will be used in your code and automatically substituted with a proper value based on the chosen language.
  • Keys can be nested (this is especially useful for larger sites with many translations).
  • Keys support interpolation: take a look at the {company} part in the example above. This placeholder will be replaced with an actual company name that we are going to provide in the code. If you are a fan of Ruby on Rails (like me), then you may also use Rails-style placeholders: %{company}.

Now add Russian translations to the locales/ru.json file:

Great! The translations are ready, and we can use them in our app.

Uploading Translation Files to Lokalise

After creating the initial translation files, we can upload them to the Lokalise project we created earlier. To achieve this, run the following commands:

PROJECT_ID is the identifier that you received in the previous step when creating a new project.

Using Vue I18n in Templates

Now let’s see how to utilize the created translations in our pages. In fact, all you need to do is utilize a $t function and pass a translation key to it. Let’s tweak the template within the App.vue file:

main.welcome is the translation key. We are using dot (.) because the key is nested. The company: 'Lokalise' part provides the value for the {company} placeholder within the translation file.

We are not going to use the default HelloWorld component, so remove the following line from the App.vue file:

Also, remove HelloWorld from the components property and delete the components/HelloWorld.vue file.

Now you may boot the app:

Proceed to localhost:8080 — the welcoming message should be displayed for you. In order to make sure that the Russian translation works as well, you can open the i18n.js file and set 'ru' as the locale property:

Don’t forget to undo the above change once you’re done testing!

Downloading Translation Files from Lokalise

Once you have edited your translations on Lokalise, download them back into your project by running:

Changing the Language

So, our application is now multilingual, but there’s no option to actually switch between locales via the user interface. Let’s add this feature now!

I suggest creating a new component called LocaleSwitcher which is going to handle all switching logic. Create a new src/components/LocaleSwitcher.vue file:

This is a basic unordered list which is going to contain our supported locales. Once the list item is selected, we call up the switchLocale() method and perform the actual change.

The next step is to provide an array of supported locales. We can just hard-code them, but that is not very convenient. Instead, let’s take advantage of the .env file which I mentioned earlier. Add the following line:

Now use this environment variable to produce an array of locales within the LocaleSwitcher.vue:

process.env enables us to access environment variables. Then we just take the required value and use split() to produce an array.

Lastly, add a switchLocale() method:

this.$i18n.locale allows us to get and set the current locale of the app. We first check if the requested locale is different from the currently chosen one and update it if necessary.

To make the list elements look more like links, you may add the following scoped style to the component:

Once you are ready, use the new component within App.vue:

Reload the application, proceed to localhost:8080 and try clicking the switcher links. The welcoming message should be translated to the chosen language. Good job!

Exploring Vue I18n Features

Pluralization

One of the most common internationalization tasks is pluralizing the text properly. To demonstrate it in action, let’s show how many new messages the user has. Start with the English translation and provide the new_message key:

Here we provide three possible translations separated with pipeline (|) which will be picked automatically, based on the passed number. The first translation (no messages) is optional and may be omitted.

Pluralization rules in English are quite simple as the word may have only two forms. For Russian, things become more complex:

Unfortunately, Vue I18n does not support complex pluralization out of the box. It is quite simple to add this feature though. Modify the i18n.js file like this:

Basically, we are explaining what translation to choose based on the provided number. Pluralization algorithms for all languages may be found on the Unicode CLDR website.

With the above code in place, we may implement pluralization in the code. Add a new line to the App.vue file:

Note that in order to employ pluralization, you need to use a $tc function. It accepts the following three arguments:

  • Translation key.
  • The number to use in pluralization.
  • Optional object with the interpolation values. By default, the second argument will be provided as an interpolation value, but you may override it. For example: $tc('main.new_message', 10, {count: "Not many"}).

Date and Time

The next common feature that I would like to show you is localization of date and time. In order to support it, we need to provide one or more datetime formats within the i18n.js:

For both locales we have added a new format called short:

  • The year and day will be provided as numbers.
  • The name of the month will be displayed in a shortened form (for example, Apr).

You can add other formats as necessary by using the options listed in ECMA-402.

Now, let’s localize the current date using the short format. Add a new line to the App.vue file as follows:

$d is a function that will perform localization. new Date() returns the current date, whereas short is the name of our format. Sweet!

Working with Currency

The last Vue I18n feature that I am going to show you is formatting numbers and representing them with the proper currencies. To add currency formats, we need to tweak the i18n.js file again:

So, for the English locale we’ll be using US dollars, whereas for Russian we’ll use roubles.

Next, add another new line to the App.vue file:

$n is a function for localizing numbers. It accepts the actual number and the name of the format.

Vue I18n docs provide some more examples explaining how to add custom formatting for your numbers.

Setting the Language as a Route Parameter

At this point, our application is translated into two languages. However, we do not persist the chosen locale anywhere. Also, whenever a user visits our site, an English locale is being set by default. In this section we’ll see how to enhance our application further with the help of Vue Router.

Installing Vue Router

The first step is installing Vue Router itself:

During the installation, choose to use history mode.

The above command is going to perform the following operations:

  1. Tweak main.js to enable routing.
  2. Add sample router links and a router-view to the App.vue.
  3. Create a router/index.js file with initial configuration.
  4. Add two sample views (within the views folder).

Managing Views

What I would like to do next is tweak the App.vue file and update the sample views created for us in the previous section. Start by tweaking the App.vue. We are going to bring the language switcher back as well as introduce a new MainMenu component:

Next, create a new components/MainMenu.vue file which is going to contain the router links generated for us during router installation:

Add new translations for the links. English:

And Russian:

Now we need to tweak the sample views generated for us. The views/Home.vue will contain the translated messages which were displayed on the main page:

The views/About.vue will simply display a welcoming message:

Provide translations for the about.welcome key:

Adding Routes with Vue I18n Support

The views are ready, and we can proceed to our routes. Replace the contents of the router/index.js file with the following:

load() is a small helper function that we will use to load the proper view based on the current router.

Now add the actual routes as follows:

/:locale is a variable part of the route which will equal either en or ru. For example:localhost:8080/en/about. There are also two child routes for our Home and About views. Home is the default page; therefore, its path is set to an empty string (it can be accessed with locahost:8080/en).

When the /:locale page is initially entered, we need to set a proper locale based on the parameter. Therefore, add a beforeEnter property:

The logic is pretty simple:

  1. We fetch the requested locale from the route by using to.params.locale.
  2. We also generate an array of supported locales.
  3. If the requested locale is not supported (that is, not found in the array), we set the locale to English and redirect the user to localhost:8080/en.
  4. If the locale is supported and the current locale is different, we switch to the chosen language.
  5. Lastly, navigate the user to the page.

We may also handle all other routes and redirect the user to the default locale:

Lastly, create the router:

The routes are now configured properly!

Adjusting the Navigational Links

The links within the components/MainMenu.vue file also require some tweaks:

Here we utilize named routes (Home and About respectively). These named routes were set in the previous step using the following line: name: 'Home'. For each route we also provide the currently set locale.

If you boot the server now, you will probably get an error saying that the template compiler is not available. To fix it, add the following property to the vue.config.js file:

The navigational links and language switcher should work now. One problem, however, is that after changing a language, the locale is not being updated in the URL. Let’s fix that as well!

Rewriting URL After Locale Switch

Updating a URL after a locale switch is actually a very simple thing to do. We need to add a single line to the components/LocaleSwitcher.vue file:

First, we are generating the proper URL based on the chosen locale. Then, this.$router.push will navigate the user to a new URL (it is possible to return to the previous one thanks to the history mode).

Now if you change the locale, the URL will be updated for you. Try playing around with the links to make sure everything works properly!

Introducing Lazy Loading

Our application is working but there is one important feature missing: lazy loading of translation files. Usually, loading translations for all languages in an overkill. Therefore, in this section we will see how to implement this feature.

Introducting Translation Plugin

Before implementing lazy loading, however, it would be a good idea to refactor our code. Specifically, I would like to extract all localization-related logic to a separate file. Therefore, let’s create a new plugins/Translation.js file:

There are three getters to read:

  • The default locale
  • The list of supported locales
  • The currently set locale

Also, we have one setter to change the current language.

Now, let’s implement a method to change the language and load the necessary translation file:

This method is based on promises. If the locale is not supported, then we just reject with an error message. If the chosen locale is the same, we resolve the promise with that locale. Otherwise, load the corresponding translation file, pass translation messages to Vue I18n, switch the locale, and return it.

Here is the method to check if the requested locale is supported:

Method to load a translation file:

Method to switch locale:

Note that it also updates the lang attribute of the html tag.

Let’s also add a special method that will be used in our routing:

This method has the same logic as the one provided in the beforeEnter() method, but it relies on the newly created plugin.

Lastly, I’d like to introduce a special method to generate localized routes. It is going to accept the route name:

Our plugin is ready so we may refactor the code based on it!

Refactoring I18n Config

The next step is to update our i18n.js file to take advantage of the new Translation plugin. Here is a new version of this file:

Main things to note here:

  1. Initially, we are loading only the English translation file (as English is set as the default locale).
  2. We are exporting an i18n constant instead of using just export default.
  3. messages now contains only the imported English translations.
  4. loadLocaleMessages function is removed because we have implemented our own loader inside the Translation plugin.

Refactoring Main File and Routes

Next, adjust the contents of the main.js file in the following way:

There are two things to note here:

  1. Make sure to import all the necessary modules properly.
  2. Allow $i18nRoute to be used in your templates.

Next, tweak the router/index.js file:

Note the following:

  1. We are now importing only the Translation plugin which contains all locale-related logic.
  2. beforeEnter now delegates to the routeMiddleware. This way we are making our code less cluttered and separate the logic into the proper files.
  3. The default locale is also fetched using the new plugin.

Great job!

Refactoring Components

We are nearly done with all the refactoring. The last thing to take care of are our components. Start with the components/LocaleSwitcher.vue:

Main things to note:

  1. We are using the supportedLocales attribute which is defined below.
  2. We also translate the locale codes.
  3. Don’t forget to load the Translation plugin.
  4. Introduce a new supportedLocales computed attribute which relies on the Translation.supportedLocales getter.
  5. Locale is now also changed using our plugin.

New English translations:

Russian translations:

Finally, adjust the components/MainMenu.vue:

Here we are taking advantage of the $i18nRoute() helper to generate localized routes based on the currently set locale.

At this point you may boot your application and make sure everything is working!

Reading User Preferred Language

The very last thing I wanted to should you today is the ability to adjust the initial locale based on the user’s preferred language. Usually, browsers send preferred language in the request so we can take advantage of this fact. To get started, install axios library which will be used to work with the headers:

Import axios inside plugins/Translation.js file:

Add a new method that will try to read the preferred locale and check whether it is supported:

The logic of this method is rather simple:

  1. We read the preferred locale.
  2. If the app supports this locale, return it.
  3. If the locale is unknown, try to strip the ISO code and check again.
  4. Finally, if both checks were unsuccessful, return the default locale.

Here is the implementation of the getUserLocale() method:

  1. Try to read the preferred language. If the preferred language is not set, simply use the default locale.
  2. Return full locale (for example, en-us) as the first attribute of the object.
  3. Return locale without the ISO part (for example, en) as the second attribute.

Having these two methods in place, adjust the routeMiddleware method:

There is only one change. If the requested locale is not supported, we fetch the preferred locale.

Lastly, set the Accept-Language header using axios:

That’s all! Now the application will try to use the language preferred by the current visitor.

Conclusion

In this tutorial we have seen how to implement internationalization and localization using the Vue I18n solution. We have learned how to configure this library, perform translations, use pluralization, and localize datetime and numbers. On top of that, we’ve added a language switcher, enabled Vue Router, introduced lazy loading, and support for the user preferred locale. Not bad for a single article!

Of course, this demo app can be enhanced further. To get some inspiration you may check the example i18n-starter repo created by Dobromir Hristov. Also, you may be interested in a vue-i18n-extract tool which scans your project and extracts translations into JSON files. Don’t hesitate to post a comment if you have any additional questions or concerns.

Thank you for visiting us today and until the next time!

Further reading

Set up your Vue.js website with i18n support to reach more customers

Grab a FREE Lokalise trial and start internationalizing your app so you can improve the multilingual customer experience of your website.
Start now