6
votes

Is there any way to share props between components using the composition API, or should I still resort to mixins for that?

For example, I have a "visible" prop that I want to reuse on 5 components. How can I define it in 1 common place and reuse it with the composition API?

With a mixin I would have done it the old fashioned way:

const mixin = {
   props: { visibile: { type: Boolean: required: false } }
}

Used in the component:

mixins: [theMixinAbove]

How can I accomplish this using the composition API?

1
I don’t really understand what you mean by “sharing” props. Each component has its own props.Martin Bean
The API for mixins doesn't seem to have changed in Vue 3 and, as far as I can tell, there isn't any other way to achieve this.Daniel_Knights
@Daniel_Knights Alright, but if I resort to mixins with composition API, I can't get type safety, right?filur
I can't actually get a mixin to work with props in the way you've described. Have you tested it and know that it works?Daniel_Knights
@Daniel_Knights Hmm, maybe I'm misunderstanding you but yeah I've done it multiple times with the options API, it's just a matter of reusing a mixin. Right now I'm thinking about using PropType<MyProps> instead, guess that's a viable option...filur

1 Answers

2
votes

You can do it, but I think you'll need to implement props as-well in a similar manner, and you can't do it during setup because at that point, the props are already expected.

For example you can define a function that lives with your other function you would use during setup, and then destructure it into the rest of your props

props:{myInternalProp:String, ...withVisibilityProps()},

const app = Vue.createApp({})

app.component('my-component', {
  template: '<h1>My Component is {{visiblity}}</h1>',
  props:{...withVisibilityProps()},
  setup(props){
    return({...withVisibility(props)})
  }
})

function withVisibility(props) {
  return {visiblity:Vue.ref(props.visible?"visible":"not visible")};
}
function withVisibilityProps() {
    return {visible:Boolean};
}

app.mount('#app')
<script src="https://unpkg.com/[email protected]/dist/vue.global.prod.js"></script>
<div id="app">
  <my-component :visible="true"></my-component>
  <my-component :visible="false"></my-component>
</div>

note that the setup function is used to handle the visibility variable. If you only need the prop, you can skip the withVisibility and setup