205. Can I use dynamic directive null value for slots?
No. It can be applied only for v-bind and v-on but not v-slot. This is because v-slot is not a binding and cannot be removed.
206. What is Vue I18n plugin?
Vue I18n is an internationalization plugin of Vue.js. It easily integrates some localization features to your Vue.js Application. The simple usage with in html would be as below,
```javascript
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-i18n/dist/vue-i18n.js"></script>
<div id="app">
<p>{{ $t("user.message") }}</p>
</div>
```
and after that configure them in javascript
```javascript
// Ready translated locale messages
const messages = {
en: {
user: {
message: 'Good morning'
}
},
de: {
user: {
message: 'Guten Morgen'
}
}
}
// Create VueI18n instance with options
const i18n = new VueI18n({
locale: 'de', // set locale
messages, // set locale messages
})
// Create a Vue instance with `i18n` option
new Vue({ i18n }).$mount('#app')
```
The output is going to be like this,
<div id="#app">
<p>Guten Morgen</p>
</div>
207. What are the types of formatting?
Basically there are 4 types of formatting available in i18n plugin,
1. **Named formatting:** First You need to define the message keys in curly braces({})
```javascript
const messages = {
en: {
message: {
greeting: '{msg} Morning'
}
}
}
```
After that pass argument value along with key in the template
```javascript
<p>{{ $t('message.greeting', { msg: 'Good' }) }}</p>
```
It outputs the result as below,
```javascript
<p>Good Morning</p>
```
2. **List formatting:** First you need to define zero index based keys in the messages,
```javascript
const messages = {
en: {
message: {
greeting: '{0} Morning'
}
}
}
```
After that pass argument value with in an array
```javascript
<p>{{ $t('message.greeting', ['Good']) }}</p>
```
Finally it outputs the result as below,
```javascript
<p>Good morning</p>
```
**Note:** It also accepts array-like object
```javascript
<p>{{ $t('message.greeting', {'0': 'Good'}) }}</p>
```
3. **HTML formatting:** This formatting is required when want to render your translation as an HTML message and not a static string.
```javascript
const messages = {
en: {
message: {
greeting: 'Good <br> Morning'
}
}
}
```
After that use it in the html directive template as below
```javascript
<p v-html="$t('message.greeting')"></p>
```
Finally it outputs the result as below
```javascript
<p>Good
<!--<br> exists but is rendered as html and not a string-->
Morning</p>
```
4. **Ruby on rails format:** First you need to define with percentile and curly braces as below,
```javascript
const messages = {
en: {
message: {
greeting: '%{msg} Morning'
}
}
}
```
After that pass argument with key similar to named formatting
```javascript
<p>{{ $t('message.greeting', { msg: 'Good' }) }}</p>
```
Finally it renders the output as below,
```javascript
<p>Good Morning</p>
```
208. What is custom formatting?
You can use custom formatting for some of the formatting cases such as ICU formatting syntax (message "pattern" strings with variable-element placeholders enclosed in {curly braces}). It implement Formatter Interface.
```javascript
// Custom Formatter implementation
class CustomFormatter {
constructor (options) {
// ...
}
interpolate (message, values) {
// return the interpolated array
return ['resolved message string']
}
}
// register with `formatter` option
const i18n = new VueI18n({
locale: 'en-US',
formatter: new CustomFormatter(/* here the constructor options */),
messages: {
'en-US': {
// ...
},
// ...
}
})
// Run!
new Vue({ i18n }).$mount('#app')
```
209. How do you handle Pluralization?
You can translate with pluralization by defining the locale that have a pipe | separator, and define plurals in pipe separator. Remember that template should use $tc() instead of $t().
First you need to difine the messages,
```javascript
const messages = {
en: {
user: 'user | users',
friend: 'no friend | one friend | {count} friends'
}
}
```
And the template can configure the messages with values
```javascript
<p>{{ $tc('user', 1) }}</p>
<p>{{ $tc('user', 10) }}</p>
<p>{{ $tc('friend', 0) }}</p>
<p>{{ $tc('friend', 1) }}</p>
<p>{{ $tc('friend', 10, { count: 10 }) }}</p>
```
Finally it outputs the result as below
```javascript
<p>user</p>
<p>users</p>
<p>no friend</p>
<p>one friend</p>
<p>10 friends</p>
```
210. How to implement DateTime localization?
You can localize the datetime with definition formats(e.g. short, long, etc).
Lets follow below steps to localize date and time
1. For example, you can add definition formats for English and Jappan locale as below
```javascript
const dateTimeFormats = {
'en-US': {
short: {
year: 'numeric', month: 'short', day: 'numeric'
},
long: {
year: 'numeric', month: 'short', day: 'numeric',
weekday: 'short', hour: 'numeric', minute: 'numeric'
}
},
'ja-JP': {
short: {
year: 'numeric', month: 'short', day: 'numeric'
},
long: {
year: 'numeric', month: 'short', day: 'numeric',
weekday: 'short', hour: 'numeric', minute: 'numeric', hour12: true
}
}
}
```
2. After that You need to specify the dateTimeFormats option of VueI18n constructor
```javascript
const i18n = new VueI18n({
dateTimeFormats
})
new Vue({
i18n
}).$mount('#app')
```
3. And then add them to the template
```javascript
<div id="app">
<p>{{ $d(new Date(), 'short') }}</p>
<p>{{ $d(new Date(), 'long', 'ja-JP') }}</p>
</div>
```
4. Finally it outputs the result
```javascript
<div id="app">
<p>May 20, 2019</p>
<p>2019年5月20日</p>
</div>
```
211. How do you implement Number localization?
You can localize the number with definition formats(e.g. currency, etc)
Lets follow below steps to localize numbers
1. You need to add definition formats. For example, lets add it for English and Japanese locales
```javascrippt
const numberFormats = {
'en-US': {
currency: {
style: 'currency', currency: 'USD'
}
},
'ja-JP': {
currency: {
style: 'currency', currency: 'JPY', currencyDisplay: 'symbol'
}
}
}
```
2. After that specify the numberFormats option of VueI18n constructor
```javascript
const i18n = new VueI18n({
numberFormats
})
new Vue({
i18n
}).$mount('#app')
```
3. Now let's configure them in template
```javascript
<div id="app">
<p>{{ $n(10, 'currency') }}</p>
<p>{{ $n(50, 'currency', 'ja-JP') }}</p>
</div>
```
4. Finally it outputs the result
```javascript
<div id="app">
<p>$10.00</p>
<p>¥50</p>
</div>
```
212. How do you perform locale changing?
All child components of a root instance are localized using the locale property of the VueI18n class. You can change the value of the locale property of the VueI18n instance as below.
```javascript
const i18n = new VueI18n({
locale: 'de', // set locale
...
})
// create root Vue instance
new Vue({
i18n,
...
}).$mount('#app')
// change other locale
i18n.locale = 'en'
```
You can also use component's VueI18n instance referenced as the $i18n property which will be used to change the locale.
```javascript
<template>
<div class="locale-changer">
<select v-model="$i18n.locale">
<option v-for="(lang, i) in langs" :key="`Lang${i}`" :value="lang">{{ lang }}</option>
</select>
</div>
</template>
<script>
export default {
name: 'locale-changer',
data () {
return { langs: ['de', 'en'] }
}
}
</script>
```
213. What is Lazy loading translations?
The loading of all translation files at once is unnecessary and it may impact the performance too. It will be easy for lazy loading or asynchronously loading the translation files when you use webpack. i.e, You can dynamically load or import language translations using webpack as below,
```javascript
//i18n-setup.js
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import messages from '@/lang/en'
import axios from 'axios'
Vue.use(VueI18n)
export const i18n = new VueI18n({
locale: 'en', // set locale
fallbackLocale: 'en',
messages // set locale messages
})
const loadedLanguages = ['en'] // our default language that is preloaded
function setI18nLanguage (lang) {
i18n.locale = lang
axios.defaults.headers.common['Accept-Language'] = lang
document.querySelector('html').setAttribute('lang', lang)
return lang
}
export function loadLanguageAsync (lang) {
if (i18n.locale !== lang) {
if (!loadedLanguages.includes(lang)) {
return import(/* webpackChunkName: "lang-[request]" */ `@/lang/${lang}`).then(msgs => {
i18n.setLocaleMessage(lang, msgs.default)
loadedLanguages.push(lang)
return setI18nLanguage(lang)
})
}
return Promise.resolve(setI18nLanguage(lang))
}
return Promise.resolve(lang)
}
```
After that loadLanguageAsync function can be used inside a vue-router beforeEach hook.
```javascript
router.beforeEach((to, from, next) => {
const lang = to.params.lang
loadLanguageAsync(lang).then(() => next())
})
```
214. What is the main difference between method and computed property?
The main difference between a computed property and a method is that computed properties are cached and invoke/change only when their dependencies change. Whereas a method will evaluate every time it's called.
215. What is vuetify?
Vuetify is a semantic component material framework for Vue. It aims to provide clean, semantic and reusable components that make building application easier. The installation and configuration is simple as below,
```javascript
npm install Vuetify
```
```javascript
import Vue from 'vue'
import Vuetify from 'vuetify' // Import Vuetify to your project
Vue.use(Vuetify) // Add Vuetify as a plugin
```
216. How do you watch for nested data changes?
You can use deep watcher by setting `deep: true` in the options object. This option enables us to detect nested value changes inside Objects.
```javascript
vm.$watch('someObject', callback, {
deep: true
})
vm.someObject.nestedValue = 123
// callback is fired
```
**Note:** This is not required to listen for Array mutations.
217. How to trigger watchers on initialization?
You can use `immediate: true` option in order to trigger watchers when the vue instance (or component) is being created. i.e This option will trigger the callback immediately with the current value of the expression.
```javascript
watch: {
test: {
immediate: true,
handler(newVal, oldVal) {
console.log(newVal, oldVal)
},
},
},
```
218. What is the purpose of comments option?
When `comments` option enabled, it will preserve and render HTML comments found in templates. By default, it's value is false. Let's see the action in an example,
```javascript
<template>
<div class="greeting">
<!--greeting-->
<h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
comments: true,
data () {
return {
msg: 'Good morning'
}
}
}
</script>
```
**Note:** This option is only available in the full build, with in-browser compilation. i.e, It won't work with Single File Components(SFC).
219. How to identify whether code is running on client or server?
You can use `vm.$isServer` method to know whether the current Vue instance is running on the server or client. The usage would be as below,
```javascript
const Vue = require('vue');
Vue.prototype.$isServer
(OR)
this.$isServer // With in component
```
220. How do you watch route object changes?
You can setup a watcher on the `$route` in your component. It observes for route changes and when changed ,sets the message property.
```javascript
watch:{
$route (to, from){
this.message = 'Welcome';
}
}
```
221. How do you sync current route in vuex store?
You can use `vue-router-sync` library to sync current $route object in vuex store's state. The usage is quite straight forward with two steps
1. **Installation:**
```bash
npm install vuex-router-sync
```
2. **Sync router and store:**
```javascript
import { sync } from 'vuex-router-sync'
import store from './vuex/store' // vuex store instance
import router from './router' // vue-router instance
const unsync = sync(store, router) // Returns an unsync callback function
unsync() // Unsyncs store from router
```
222. What are navigation guards in vue router?
The navigation guards of vue-router are used to protect navigations either by redirecting it or canceling it. Below are the 3 different ways to hook into router navigations
1. Global:
2. Per-route:
3. In-component:
223. Can I use computed property in another computed property?
Yes, you can access it directly as you would data props. For example, the comboTwo computed property uses comboOne computed property as below,
```javascript
data() {
return {
propOne: 'prop1',
propTwo: 'prop2'
}
},
computed: {
comboOne() {
return this.propOne + ',' + this.propTwo;
},
comboTwo() {
return this.comboOne.split(',').join('-');
}
}
```
224. How can I use imported constant in template section?
The variables need to be exposed on your data in order to use them in template section. i.e, You can't use them directly on template.
```javascript
<span>
CREATE: {{CREATE_PROP}}
UPDATE: {{UPDATE_PROP}}
DELETE: {{DELETE_PROP}}
</span>
<script>
import {CREATE_DATA, UPDATE_DATA, DELETE_DATA} from 'constants';
new Vue({
...
data:{
CREATE_PROP: CREATE_DATA,
UPDATE_PROP: UPDATE_DATA,
DELETE_PROP: DELETE_DATA
}
...
})
</script>
```
225. Is recommended to use async for computed properties?
No, it is not recommended. Computed properties should be synchronous. But if you still use asynchronous actions inside them, they may not work as expected and can lead to an unexpected behaviour. For example, the below usage of async/await is not recommended,
```javascript
async someComputedProperty () {
return await someFunction()
},
```
**Note:** If you still prefer to use async computed properties for some reason then you can consider using additional plugin such as `vue-async-computed`.
Comments
Post a Comment
please do not enter any spam link in the comment box