vue --- > 获取子组件数据的一个应急方案$refs

使用$refs需要注意以下2点:
1.html方法使用子组件时,需使用ref = “xxx” 声明.
2.在父组件中使用,this.refs.xxx.msg 获取数据

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>

<div id="app">
    <p>{{ message }}</p>
    <my-component ref="comA"></my-component>
    <button @click="handleRef">ref获取子组件数据</button>
</div>
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<script>
    
    
    Vue.component('my-component',{
        template:'<button @click="sendMessage">派发事件</button>',
        data:function(){
            return {
                msg:'来自子组件'
            }
        }
       
    })
    const app = new Vue({
        el:'#app',
        data:{
            message: ''
        },
        methods:{
            handleRef:function(){
                this.message = this.$refs.comA.msg
            }
        }
    })
</script>
</body>
</html>

在这里插入图片描述
参考《Vue.js实战》P82

猜你喜欢

转载自blog.csdn.net/piano9425/article/details/94406777
今日推荐