Search code examples
javascriptvue.jsnuxt.jsmixins

how to pass data to mixins and then displaying them in your component?


I want to pass data to my mixin's method, and then display it in my component. Something like:

//component A

mixins: [mixinOne],
data(){
  return{
    val = null
  }
},
mounted(){
  this.mixinMethod('good value', this.val);
}
//mixinOne
mixinMethod(valOne, valTwo) {
  valTwo = valOne;
}

And in my template I want to display val:

// component A
<template>
  {{val}}
</template>

I have written the above code and it doesn't work. It returns null for {{val}}! So basically I want to see 'good value' in my component for {{val}} which is setup through my mixin. How can I do that?


Solution

  • You Should put your Data section in mixin then change it and render it in your component.

    // MmixinOne
    data () {
      return {
        val = null
      }
    },
    methods: {
      mixinMethod (valOne, valTwo) {
         valTwo = valOne
      }
    }
    
    // Component A
    <template>
      {{val}}
    </template>
    
    <script>
    import MmixinOne from './MmixinOne'
    
    export default {
      mixins: [MmixinOne],
      mounted () {
        this.mixinMethod('good value', this.val)
      }
    }
    </script>
    

    Anyway you dont need a method to set value on "val". you can just set your value directly in mounted:

    mounted () {
      this.val = 'good value'
    }