与合成API共享道具



是否有任何方法可以在使用组合API的组件之间共享道具,或者我是否仍然应该使用mixin?

例如,我有一个";可见";我想在5个组件上重复使用的道具。如何在一个公共位置定义它,并将其与组合API一起重用?

如果有混音器,我会用老式的方式:

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

用于组件:

mixins: [theMixinAbove]

如何使用组合API来实现这一点?

你可以这样做,但我认为你也需要以类似的方式实现props,而且你不能在设置过程中这样做,因为在那一点上,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/vue@3.0.4/dist/vue.global.prod.js"></script>
<div id="app">
<my-component :visible="true"></my-component>
<my-component :visible="false"></my-component>
</div>

请注意,setup函数用于处理visibility变量。如果你只需要道具,你可以跳过withVisibilitysetup

您可以在compositable中使用script setupdefineProps。https://vuejs.org/api/sfc-script-setup.html#defineprops-定义

最新更新