Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

vue.js - Vue Composition API: Defining emits

When defining custom events Vue encourages us to define emitted events on the component via the emits option:

app.component('custom-form', {
  emits: ['inFocus', 'submit']
})

Using Vue 3's composition API, when a standalone composition function emits custom events, is it possible to define these in the composition function?

question from:https://stackoverflow.com/questions/65844419/vue-composition-api-defining-emits

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, because composition functions are used inside the setup hook which has not access to the other options like methods and emits :

export default defineComponent({
    name: "layout",
     emits: ['showsidebar']
    setup(props,{emit}) {
        const showSidebar = ref(true);
        const {
            breakpoints
        } = useBreakpoint();
        watch(breakpoints, (val) => {
            showSidebar.value = !(val.is === "xs" || val.is === "sm");
            emit('showsidebar',showSidebar.value )
        });
        return {
            showSidebar,
        };
    },
    data() {
        ...
    },

in the example above useBreakpoint offers only some logic that component could use it to behave, if there's some way to define that emits option in composition function, this function will always emit that event even if that function is used inside the component defines the handler of emitted event.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...