Vue中父组件访问子组件的方式--$children与$refs

1.通过$children
不常用,因为通过数组下标才能拿到具体的子组件,有不确定性;

2.$refs


demo:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <cpn></cpn>
        <cpn></cpn>
        <cpn ref="myCpn"></cpn>
        <button @click="btnClick">按钮</button>
    </div>
    <template id="cpn">
        <div>
            <h2>我是子组件</h2>
        </div>
    </template>
    <script src="../vue.js"></script>
    <script>
        const app = new Vue({
            el:"#app",
            data:{

            },
            methods: {
               btnClick(){
                // this.$children[0].showMessage();   //不常用
                // console.log(typeof this.$children);
                this.$refs.myCpn.showMessage();    //常用
               } 
            },
            components:{
                cpn:{
                    template:"#cpn",
                    methods:{
                        showMessage(){
                            console.log("showMessage");
                        }
                    }
                }
            }
        });
    </script>
</body>
</html>
发布了43 篇原创文章 · 获赞 19 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qianlixiaomage/article/details/104175557
今日推荐