Details and examples of Vue's ref

Keywords: Vue Javascript

Although there are prop s and events, sometimes you may need to access a subcomponent directly in JavaScript. To do this, you can assign an ID reference to this subcomponent through the ref feature. Ref can be added to the parent component or the child component, and can be accessed through this.refs instance. The following example implements the function of page opening input focus.

1, ref added to parent component

<body class="">
    <div id="example">
        <base-input ref="usernameInput"></base-input>
    </div>
    <script src="js/vue-2.5.13.js"></script>
    <script>
    Vue.component('base-input', {
        data: function() {
            return {
                initValue: "hi"
            }
        },
       
        template: '<input type="text"  v-bind:value="initValue">'
    })
    var app7 = new Vue({
        el: "#example",

        mounted: function() {
            console.log(this.$refs.usernameInput.$el)
            this.$refs.usernameInput.$el.focus()
            //this.$refs.usernameInput refers to a subcomponent
        }

    })
    </script>
</body>

2, ref added to subcomponent

<body class="">
    <div id="example">
        <base-input ref="usernameInput"></base-input>
    </div>
    <script src="js/vue-2.5.13.js"></script>
    <script>
    Vue.component('base-input', {
        data: function() {
            return {
                initValue: "hi"
            }
        },
        mounted: function() {
            this.$refs.input.focus()
        },
        template: '<input type="text" ref="input" v-bind:value="initValue">'
       
    })
    var app7 = new Vue({
        el: "#example",
    })
    </script>
</body>

Conclusion: ref is mainly used to obtain elements in special cases. If ref is added to the parent component, this.$refs.usernameInput.$el.focus() must be added with $el.

Posted by xyn on Fri, 31 Jan 2020 08:53:20 -0800