组件基础-使用ref属性标识元素或组件

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>

    <div id="app">
        <h1>{{rootMesage}}</h1>
        <!-- 使用 ref 特殊属性标识组件 -->
        <child1-component ref="child1"></child1-component>
        <child2-component ref="child2"></child2-component>
        <!-- 使用 ref 特殊属性标识元素 -->
        <h2 ref="heading2">使用 ref 特殊属性标识元素</h2>
        <button type="button" @click="onClick">改变 h2 的颜色</button>
    </div>

    <script src="./vue.js"></script>
    <script>


        const app = new Vue({
            el: '#app',
            data: {
                rootMesage: 'app根组件的数据'
            },
            methods: {
                onClick() {
                    // 通过 this.$refs.heading2 获取 DOM 元素,并为其添加样式
                    this.$refs.heading2.style.color = 'red'
                }
            },
            mounted() {
                // 使用实例属性 $refs 获取子组件
                console.log(this.$refs.child1)
                console.log(this.$refs.child2)

                // 使用实例属性 $refs 获取DOM元素
                console.log(this.$refs.heading2)

            },
            components: {
                'child1-component': {
                    data() {
                        return {
                            child1Message: 'child1组件的数据'
                        }
                    },
                    template: '<div><h2>{{child1Message}}</h2></div>'
                },
                'child2-component': {
                    data() {
                        return {
                            child2Message: 'child2组件的数据'
                        }
                    },
                    template: '<div><h2>{{child2Message}}</h2></div>'
                }
            }
        });

    </script>
</body>

</html>
发布了151 篇原创文章 · 获赞 1 · 访问量 1858

猜你喜欢

转载自blog.csdn.net/qq_45802159/article/details/103818272