Skip to content

Instantly share code, notes, and snippets.

@oliviagardiner
Last active February 1, 2021 01:03
Show Gist options
  • Save oliviagardiner/8203e062a58b9fd4762becabfd7f46d5 to your computer and use it in GitHub Desktop.
Save oliviagardiner/8203e062a58b9fd4762becabfd7f46d5 to your computer and use it in GitHub Desktop.
Nuxt.js + vue-moment
// components/component.vue
<template lang="pug">
div {{ new Date() | moment("dddd, MMMM Do YYYY, h:mm:ss a") }}
b-form-select(:value="locale" @change="changeLocale($event)")
option(v-for="lang in locales" :value="lang" :key="lang")
i(:class="'flag-icon-' + lang").flag-icon
</template>
<script>
import { mapState } from 'vuex'
export default {
computed: {
...mapState({
locale: (state) => state.i18n.locale, // assumes you have your current locale as a string in the i18n store
locales: (state) => state.i18n.locales // assumes you have an array of locales in the i18n store
)}
},
methods: {
changeLocale (newLocale) {
// store commit logic
this.$store.commit('i18n/setLocale', newLocale)
// match your vue-moment translations to your i18n state
this.$moment.locale(newLocale)
}
}
}
</script>
// plugins/vue-moment.js
// vue-moment 4.0.0
// nuxt 1.0.0
// nuxt-i18n 1.1.0
import Vue from 'vue'
import VueMoment from 'vue-moment'
import moment from 'moment'
import 'moment/locale/hu' // whatever you import here will be set as default, no need to import all locales you intend to use
Vue.use(VueMoment, { moment })
@jumofe95
Copy link

Hi!
I have a question:
How can I pass this: {{ new Date() | moment("dddd, MMMM Do YYYY, h:mm:ss a") }} into the <script> tag?

I want, for example, save it as a variable.
Thanks!

@Soviut
Copy link

Soviut commented Jul 12, 2019

It would be good to include a comment in the plugin that explains that the following is required in nuxt.config.js

plugins: [
  '~/plugins/vue-moment.js'
]

@RonAlmog
Copy link

@Soviut, you're so right!
it would be very hard to guess.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment