Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 325
filur Avatar asked Dec 20 '20 21:12

filur


People also ask

How do you pass props in composition API?

Use defineProps to handle the passing of the show prop into ChildComponent. Deconstruct the prop using toRefs(). Then, inside the watch property, pass in show as the first parameter in order to “watch” for a change in the state of show after clicking the button.

What is Options API and composition API?

The Composition API lets us create components without the need of a large single exportable object, like in the Options API. For example, if we wanted to make a simple counter component with the Options API, it would look like the code below.

What is composition API in vue3?

The Composition API allows developers to write code with more flexibility, and it allows users to integrate TypeScript with their program. This API modifies the previously used Options API in Vue 2 and includes a relatively more straightforward way of writing data , computed , method , watches , etc.


1 Answers

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

like image 176
Daniel Avatar answered Oct 27 '22 21:10

Daniel