Fe-interview: [vue] 怎么访问到子组件的实例或者子元素?

Created on 22 Jun 2019  ·  5Comments  ·  Source: haizlin/fe-interview

[vue] 怎么访问到子组件的实例或者子元素?

vue

Most helpful comment

this.$children/this.$refs.xxx

All 5 comments

通过

this.$refs

vm.$children

this.$children/this.$refs.xxx

在子组件标签上加 ref属性如ref="baseAlert",在父组件通过this.$refs.baseAlert.子组件方法名。

写了完整的demo,你可看下

<div id="app">
    <base-input ref="usernameInput"></base-input>
</div>

<script>
    Vue.component("base-input", {
        template: "<input type='input' ref='input'>",
        methods: {
            popUp() {
                alert(11)
            },
            focus: function () {
                this.$refs.input.focus()
            }
        }
    });

    new Vue({
        el: "#app",
        data: {},
        mounted: function () {
            this.$refs.usernameInput.popUp();
            this.$refs.usernameInput.focus();
        }
    });
</script>

完整demo

Was this page helpful?
0 / 5 - 0 ratings