有没有办法使用composition在组件之间共享道具,或者我仍然应该求助于mixins呢?
例如,我有一个“可见”的道具,我想在5个组件上重用它。我如何在一个公共位置定义它,并在组合API中重用它?
有了mixin,我就可以用老式的方式来做了:
const mixin = {
props: { visibile: { type: Boolean: required: false } }
}在组件中使用:
mixins: [theMixinAbove]我如何使用composition来完成此操作?
发布于 2020-12-21 23:35:42
你可以做到这一点,但我认为你也需要以类似的方式实现道具,而你不能在安装过程中这样做,因为在这一点上,道具已经是预期的了。
例如,您可以定义一个函数,该函数与您将在安装过程中使用的其他函数共存,然后将其分解为其余的道具
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变量。如果你只需要这个道具,你可以跳过withVisibility和setup
https://stackoverflow.com/questions/65385045
复制相似问题