filur
filur

Reputation: 1556

Sharing props with composition API

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?

Upvotes: 9

Views: 3638

Answers (2)

Aito Hideki
Aito Hideki

Reputation: 103

You can use script setup and use defineProps inside the composable. https://vuejs.org/api/sfc-script-setup.html#defineprops-defineemits

Upvotes: -2

Daniel
Daniel

Reputation: 35684

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

Upvotes: 3

Related Questions