Vue子组件的索引

Laughing
2021-02-21 / 0 评论 / 1,026 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2022年11月20日,已超过826天没有更新,若内容或图片失效,请留言反馈。

在Vue中,当子组件较多时,通过this.$children来一一遍历我们需要的一个组件是比较困难的,尤其是组件动态渲染时,他们的序列是不固定的。Vue提供了子组件索引的方法,用特殊的属性ref为子组件指定一个索引的名字。

<html>

<head>
    <title>Vue学习</title>
    <script src="vue.js"></script>
</head>

<body>

    <div id="app">

        <component-a ref="compA"></component-a>

        <button @click="handleMessage">获取组件A的内容</button>

        {{message}}

    </div>

    <script type="text/javascript">

        Vue.component("component-a", {
            data: function () {
                return {
                    message: '这是组件A的message'
                }
            },
            template:'<div></div>'
        })

        var app = new Vue({
            el: '#app',
            data: {
                message: ''
            },
            methods: {
                handleMessage: function () {
                    this.message = this.$refs.compA.message
                }
            }
        })
    </script>
</body>

</html>
1

评论 (0)

取消
  1. 头像
    newlw
    Windows 10 · Google Chrome

    看密码

    回复