Vue-i18n Single File Component Not Working - vue.js

I am trying to implement v-i18n to my project with sfc method. I couldn't make it work. I will not make you confuse with my project, that's why just modified with adding 10-15 lines of code to official v-i18n sfc example.
This is very simply shows my question.
For those who prefer check this very tiny question project on github
https://github.com/berkansivri/V-i18n-Question
Component1.vue
<template>
<p>{{$t('lang')}}</p>
</template>
<i18n>
{
"en":{
"lang" : "English"
},
"es":{
"lang": "Espanol"
}
}
</i18n>
App.vue
<template>
<div id="app">
<label for="locale">locale</label>
<select v-model="locale">
<option>en</option>
<option>es</option>
</select>
<p>message: {{ $t('hello') }}</p>
<Comp1></Comp1>
</div>
</template>
<i18n>
{
"en": {
"hello": "hello"
},
"es": {
"hello": "hola"
}
}
</i18n>
<script>
import Comp1 from './components/component1'
export default {
components:{
Comp1
},
name: 'App',
data () { return { locale: 'en' } },
watch: {
locale (val) {
this.$i18n.locale = val
}
}
}
</script>
So, multiple <i18n>tag in multiple components. I just modified $i18n.locale from App.vue but it did not fire related i18n function $t('lang') on Component1, just modifies $t('hello') on itself.
How can I make it work?

using vue devtools u will find out that messages of $i18n in single file component is different from each other, so they are different objects.
u need to do is:
i18n.js
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import messages from '#/lang'
Vue.use(VueI18n)
const i18n = new VueI18n({
locale: 'cn',
fallbackLocale: 'en',
messages
})
export default i18n
App.vue
import i18n from "./i18n.js"
i18n.locale = "en"

This is intended behavior of Single file components. If you want to change all locales of all components you can use:
locale (val) {
// this.$i18n.locale = val
this.$root.$i18n.locale = val
}
See this issue.

Related

Vue import component within functional component

I have a component called SpotifyButton in the components directory that looks like this:
<template functional>
<b-button pill size="sm" :href="props.spotifyUri" class="spotify-green">
<b-img-lazy
src="~/assets/Spotify_Icon_RGB_White.png"
height="20"
width="20"
/>
View on Spotify
</b-button>
</template>
<script lang="ts">
import Vue from 'vue';
export default Vue.extend({
name: 'SpotifyButton',
props: {
spotifyUri: {
type: String,
required: true
}
}
});
</script>
I'm able to import and use this in a component in the pages directory like so without any problem:
<template>
<spotify-button :spotify-uri="artist.uri"/>
</template>
<script lang="ts">
import Vue from 'vue';
import { Context } from '#nuxt/types';
import FullArtist from '#/types/FullArtist';
import SpotifyButton from '#/components/SpotifyButton.vue';
export default Vue.extend({
name: 'ArtistPage',
components: {
SpotifyButton
},
async asyncData({ $axios, params, error }: Context) {
try {
const artist: FullArtist = await $axios.$get(`/api/artists/${params.id}`);
return { artist };
} catch (e) {
error({ statusCode: 404, message: 'Artist not found' });
}
},
data() {
return {
artist: {
name: ''
} as FullArtist
};
}
});
</script>
However if I try to import SpotifyButton into another component in the components directory in the same way, I get the following error.
Here is the ArtistPreview component, which is in the components directory:
<template functional>
<spotify-button :spotify-uri="props.artist.uri"/>
</template>
<script lang="ts">
import Vue, { PropType } from 'vue';
import SpotifyButton from '#/components/SpotifyButton.vue';
import SimpleArtist from '#/types/SimpleArtist';
export default Vue.extend({
name: 'ArtistPreview',
components: {
SpotifyButton
},
props: {
artist: {
type: Object as PropType<SimpleArtist>,
required: true
}
}
});
</script>
Am I missing something? Why does an import that works perfectly fine in a pages directory component not work in a components directory component?
This was happening because I'm using functional components. It turns out you can't nest functional components without doing some funky workarounds. Here's the GitHub issue with a few solutions.
I went with the first solution, so my ArtistPreview component now looks something like this:
<template functional>
<spotify-button :spotify-uri="props.artist.uri"/>
</template>
<script lang="ts">
import Vue, { PropType } from 'vue';
import SpotifyButton from '#/components/SpotifyButton.vue';
import SimpleArtist from '#/types/SimpleArtist';
Vue.component("spotify-button", SpotifyButton);
export default Vue.extend({
name: 'ArtistPreview',
props: {
artist: {
type: Object as PropType<SimpleArtist>,
required: true
}
}
});
</script>
Go with:
import SpotifyButton from '~/components/SpotifyButton.vue'
With Typescript is better use another approach: Add 'nuxt-property-decorator' and follow his flow.
So, you define your component as follow:
<script lang="ts">
import { Component, Vue } from 'nuxt-property-decorator'
import SpotifyButton from '~/components/SpotifyButton.vue'
#Component({
components: {
SpotifyButton
},
})
class AnotherComponent extends Vue {
...
}
export default AnotherComponent
</script>
[Nuxt Property Decorator on Github][1]
I think is important to read the official [Nuxt Typescript documentation][2] to a proper setup.
I hope it helps!
[1]: https://github.com/nuxt-community/nuxt-property-decorator
[2]: https://typescript.nuxtjs.org/

vue-i18n $t with values attribute is not translating

I am trying to import a .json file to use as the translation file.
<template>
<template v-slot:footer>
<div>{{ $t('menu.file.new.label', $i18n.locale, locale) }}</div> <--Issue outputs menu.file.new.label
</template>
</template>
<script>
import locale from '#/locales/modules/messaging.json'
export default {
data() {
return {
locale: locale
}
}
}
</script>
the locale from messaging.json does not have any errors and works if i instead added the following to the top
<i18n src="#/locales/modules/messaging.json"></i18n>
and changed the function parameters to exclude $i18n.locale and locale and it works. Unfortunately, this is not an option as i want to pass the data to a grandchild component. However, if i can configure the grandchild to use their grandparents translation data that works too..
how can i get either:
The above to work
Alternatively, use the grandparents translation data in the grandchild
Alternatively, dynamically import translation data in the grandchild based on a prop(location of translation file to be imported)
Thanks
First of all, you should create a plugin like below:
src/plugins/i18n.js:
import Vue from 'vue';
import VueI18n from 'vue-i18n';
const DEFAULT_LOCALE = 'en';
Vue.use(VueI18n);
const i18n = new VueI18n({
locale: yourLocale || DEFAULT_LOCALE, // set locale either from localStorage or config
fallbackLocale: DEFAULT_LOCALE,
messages: require('messages.json'), // set locale messages
sharedMessages: require('other.json if exist'),
silentFallbackWarn: true,
});
export default i18n;
Then call it from main.js to globalize:
import i18n from './plugins/i18n.js';
...
new Vue({
i18n,
router,
...
render: h => h(App),
}).$mount('#app');
Then if you want to go on with custom messages, you can set it with i18n block like:
<script>
data(){
...
}
methods: ...
i18n: {
messages: require(your json path....)
}
</script>
Then you can call it like:
$t('test');
I found a solution
<template>
<st-age v-bind:menus="menu" v-bind:locale="locale[$i18n.locale].menu">
<template v-slot:content>message: {{ $route.params }}</template>
<template v-slot:footer>
<div>{{ $t('menu.file.label') }}</div>
</template>
</st-age>
</template>
<script>
import menu from './menu'
import locale from '#/locales/modules/messaging.json'
export default {
data() {
return {
menu: menu,
locale: locale
}
},
i18n: {
messages: locale
},
components: {
'st-age': () => import('#/components/layout/stage/container')
}
}
</script>
<style>
</style>
locale[$i18n.locale].menu is passing the translation data i actually need and not the entire object(which works too)
in the child component, i just pass this data as a prop to the grandchild
in the grandchild i
mounted() {
this.$i18n.setLocaleMessage(this.$i18n.locale, this.locale)
}
where this.locale is the translation data and $t('file') yields whatever i set as en.menu.file in the global translation data originally imported

Vue components - recursive rendering or what is the problem here?

I'm trying to make a new Vue app with 2 components but the components don't render.
The error is - "Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the "name" option."
I read quite a bit on the problem but could not identify the problems in the code unlike with others' codes.
Seems OK to me, not the first app with components I've written :/
App:
require('../../lib/jquery.event.drag-2.2/jquery.event.drag-2.2');
require('../../lib/jquery.event.drag-2.2/jquery.event.drag.live-2.2');
require('../../lib/jquery.event.drop-2.2/jquery.event.drop-2.2');
require('../../lib/jquery.event.drop-2.2/jquery.event.drop.live-2.2');
import Vue from 'vue';
import Axios from 'axios';
Vue.prototype.$http = Axios;
import tournamentCourtManager from
'../../components/tournament/courtManager/courtManager';
import tournamentScheduleButton from
'../../components/tournament/tournamentScheduleButton';
import { store } from "../../store/store";
new Vue({
el: '#tournamentMatchSettingsApp',
store,
components: { 'tournamentCourtManager' : tournamentCourtManager,
'tournamentScheduleButton' : tournamentScheduleButton }
});
tournamentCourtManager:
<template>
<button type="submit" class="btn btn-info">
dadada
</button>
<script>
export default {
name: 'tournamentScheduleButton',
data() {
return {}
},
mounted: function mounted() {
},
methods: {
}
}
</script>
courtManager:
<template>
<div id="tournamentCourtManager">
..
</div>
</template>
courtManager JS:
export default {
name: 'tournamentCourtManager',
components: {
'match-cell': matchCell
},
data() {
return {
};
},
....
}
And the code that prompts the error -
<tournamentschedulebutton></tournamentschedulebutton>
<tournamentcourtmanager></tournamentcourtmanager>
Because you have named the components like 'tournamentCourtManager' in the components object, they must be named like <tournament-court-manager> in the template.

How to hide a paragraph using v-if through vuex?

I am trying to create a small app in which i can click on the button and hide the paragraph but i am trying to implement that using vuex.I have a paragraph in my Home.vue file and a button in my About.vue File. I want the paragraph hide conditionally in the click of the button but i want to accomplish that using vuex. How would i do that? My store.js, home.vue and About.vue are as follows.
This is how my store looks like.
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
show:true,
},
mutations: {
toggle : state => {
state.show = !state.show
}
},
actions: {
}
})
This is the Home.vue file
<template>
<p>This needs to disappear</p>
</template>
<script>
import {mapMutations} from "vuex"
export default {
computed : {
...mapMutations ([
"toggle"
])
}
}
</script>
This is the About.vue file
<template>
<div>
<button #click="toggle">Click Me</button>
</div>
</template>
<script>
import {mapMutations} from "vuex"
export default {
computed : {
...mapMutations ([
"toggle"
])
}
}
</script>
the mapMutations should be used in methods not in computed property :
methods:{
...mapMutations ([
"toggle"
])
}
like you see in the official docs :
You can commit mutations in components with this.$store.commit('xxx'), or use the mapMutations helper which maps component methods to store.commit calls (requires root store injection):

How can I pass parameters from vue custom element to a vue component?

I don't have a whole vue app, so I use custom elements to replace some elements that should be handled with vue.
I simply want to use the vue multiselect plugin in a html file.
So I tried the following:
index.ts
import Vue from "vue"
import VueCustomElement from 'vue-custom-element'
import Autocomplete from "./vue/autocomplete.vue"
Vue.use(VueCustomElement);
Vue.customElement('auto-complete', Autocomplete);
test.html
<auto-complete
v-model="value"
:options="options"
placeholder="test"
#search-change="getData"
>
</auto-complete>
test.vue
<template>
<multiselect v-model="value" :options="options" #search-change="getData"></multiselect>
</template>
<script type="ts">
const Multiselect = require('vue-multiselect').default
export default {
components: { Multiselect },
data () {
return {
value: 'test',
options: ['list', 'of', 'options']
}
},
methods: {
getData (query) {
console.log(123)
}
}
}
</script>
<style src="vue-multiselect/dist/vue-multiselect.min.css"></style>
In the output the data of the custom element is always ignored and only the parameters in the part in the .vue file is used.
How can i achieve that the parameters like placeholder or #search-change are used from the custom element?
I am also using vue-custom-elements in one of my projects.
You are passing option as props so you need to add it as a prop in your autocomplete.vue.
<template>
<multiselect v-model="value" :options="options" #search-change="getData"></multiselect>
</template>
<script type="ts">
const Multiselect = require('vue-multiselect').default
export default {
props: ['options'],
components: { Multiselect },
data () {
return {
value: 'test'
}
},
methods: {
getData (query) {
console.log('123')
}
}
}
</script>
<style src="vue-multiselect/dist/vue-multiselect.min.css"></style>