Search code examples
typescriptvue.jsmixinsvue-mixinvue-property-decorator

Vue: Properties/data of mixin is not available when defining properties/data


I have a vue mixin that stores information (world in below example), I'd like to access in several vue components, without explicitly importing it every time.

Here's the example:

<template>
  <ol>
    <li>Hello {{ world }}</li>
    <li>{{ greeting }}</li>
    <li>{{ greeting2 }}</li>
  </ol>
</template>

<script lang="ts">
import { Component, Mixins, Vue } from 'vue-property-decorator'

@Component
class MyMixin extends Vue {
  world = 'world'
}

@Component
export default class Home extends Mixins(Vue, MyMixin) {
  greeting = 'Hello ' + this.world
  greeting2 = ''

  created() {
    this.greeting2 = 'Hello ' + this.world
  }
}
</script>

The page shows:

1. Hello world
2. Hello undefined
3. Hello world

Why is 2nd not working? Is this by design? Any better idea to circumvent that than 3.?


Solution

  • This is not related to mixins this is by the design of classes, a property doesn't know the other one in declaration, but you could define greeting as computed property :

    @Component
    export default class Home extends Mixins(Vue, MyMixin) {
    
       greeting2 = ''
       
       get greeting (){
          return 'Hello ' + this.world
        }
      created() {
        this.greeting2 = 'Hello ' + this.world
      }
    }