vue如何从父组件中触发子组件的事件

1,006 阅读1分钟
##### 引导:如果你需要在父组件中能调用子组件中的方法,即父组件直接访问子组件。那么使用ref就能解决这个问题了
    const app = Vue.createApp({})
    // 子组件
    app.compontent('my-compontent',{
        template: `
            <input ref="input"/>
        `,
        mounted() {
            this.focusInput()
        },
        methods: {
            focusInput() {
                this.$refs.input.focus()
            }
        }
    })
    
    <my-compontent ref='fatherCompontent'> </my-compontent>
    
    // 父组件直接调用(其实这里使用v-if导致子组件的重新渲染亦可以达到如此的效果,只是这里为了演示这个功能)
    this.$refs.fatherCompontent.focusInput()