Roman
Roman

Reputation: 35

Vue3 / How to pass data from mixin setup() to component

I would like to pass my object based on JavaScript class from mixin to component without reactivity. I use TypeScript, so I can't set the object to this of mixin without setting types in data(). But data() reactivity breaks some thing in my object.

mixin.js:

export default {

  setup() {
    const foo = new Foo()
    
    return {
      foo,
    }
  }
    
}

component.js:

import mixin from './mixin.js'

export default {

  setup() {
    // How can I get foo here?
  }
  
}

Update 1

Yes, it is good solution for using only one foo instance for everywhere.

But how can I use different foo instances for each component?

Same as in JS classes:

class Mixin {
  foo() {
    // ...
  }
}

class Component extends Mixin {
  bar() {
    this.foo()
  }
}

Upvotes: 1

Views: 377

Answers (1)

tao
tao

Reputation: 90013

mixin.js

export const foo = new Foo()

Import (and use) foo anywhere in your app, including any setup() function:

import { foo } from './path/to/mixin'

The above uses the same instance everywhere. If you want to use different instances of foo in each separate component, mixin.js:

export const useFoo = () => new Foo()

Anywhere else:

import { useFoo } from './path/to/mixin'
const foo = useFoo()

However, take note the second approach creates a new intance of Foo() every time useFoo() is called. So once you called it, you must use foo in that component.
Calling useFoo() multiple times in the same component will generate multiple instances, unlike how you'd use useStore(), for example.


But, I'm wondering, why do you need a mixin in the first place? Why not use:

const foo = new Foo()

...in the components where you need it?
What are you trying to achieve? And, more importantly, why?

Upvotes: 2

Related Questions