moses toh
moses toh

Reputation: 13172

How can I make data, methods and computed globally in vue?

My code like this :

<template>
  <v-layout
    column
    justify-center
    align-center
  >
    <v-flex
      xs12
      sm8
      md6
    >
      ...
    </v-flex>
  </v-layout>
</template>
export default {
  data () {
    return {
      currentDate: this.$moment().format('YYYY-MM-DD')
    }
  },
  computed: {
    birthdayFormatted () {
      return this.formatBirthday(this.birthday)
    },
  },
  methods: {
    formatBirthday (date) {
      if (!date) {
        return null
      }
      const d = this.$moment(date).format('DD MMM YYYY')
      return d
    }
  }
}
<style scoped lang="scss">
  .label {
    font-weight: 500;
    font-size: 13px;
  }
</style>

For example, I have component A like that

Where do I put currentDate data, formatBirthday method and birthdayFormatted computed? So it can be read in other components

Did I put them in vuex store?

Upvotes: 2

Views: 1839

Answers (1)

Hans Felix Ramos
Hans Felix Ramos

Reputation: 4424

You can declare a Global Mixin on your vue app:

Vue.mixin({
    data () {
        return {
            currentDate: this.$moment().format('YYYY-MM-DD')
        }
    },
    computed: {
        birthdayFormatted () {
            return this.formatBirthday(this.birthday)
        },
    },
    methods: {
        formatBirthday (date) {
            if (!date) {
              return null
            }
            const d = this.$moment(date).format('DD MMM YYYY')
            return d
        }
    }
})

Then you can access to data, computed and method declared on each Vue component.

Upvotes: 3

Related Questions