鍍金池/ 問答/C++  HTML/ 使用vue如何通過父組件監(jiān)聽子組件數(shù)據(jù)變化,并觸發(fā)相應函數(shù)?

使用vue如何通過父組件監(jiān)聽子組件數(shù)據(jù)變化,并觸發(fā)相應函數(shù)?

如題,我想要在vue父組件中監(jiān)聽子組件的數(shù)據(jù)變化,當數(shù)據(jù)變化的時候,觸發(fā)父組件相應的函數(shù)。
以下僅為示意代碼,并非項目源碼,根據(jù)項目實際情況,請勿使用 $emit以及vuex來實現(xiàn)通信

父組件:

<template>
    <div class="parent">
        <child-component ref="child"></child-component>
        <div class="tips">這里是父組件的數(shù)據(jù):{{a}}</div>
    </div>
</template>

<script>
    import ChildComponent from "./ChildComponent.vue"
    export default{
        name: 'ParentComponent',
        computed:{
            a:{
               get(){
                   this.fn(this.$refs.child.a);
                   return this.$refs.child.a;
               } 
            }
        },
        methods:{
            fn(val){
                alert(val);
            }
        },
    }
</script>

子組件:

<template>
    <div class="child">
        <div class="btn" @click="add">+1</div>
        <div class="tips">這里是子組件的數(shù)據(jù):{{a}}</div>
    </div>
</template>

<script>
    import ChildComponent from "./ChildComponent.vue"
    export default{
        name: 'ParentComponent',
        data(){
            return{
                a: 0
            }
        },
        methods:{
            add(){
                this.a ++;
            }
        },
    }
</script>

求各位支招解決,謝謝。

回答
編輯回答
厭遇

= =你這個問題直接用官方的方式就能實現(xiàn),你子組件自行監(jiān)聽自己的數(shù)據(jù)變化,然后$emit去調(diào)用父組件的方法就行了.
父組件在引用子組件時添加屬性 @方法名A="父組件定義的方法" ,然后子組件中watch屬性的變化,變化后執(zhí)行 this.$emit('方法名A'),就可以出發(fā)"父組件定義的方法"
具體代碼我就不貼了可以查看想 官方文檔的 emit和父子通信相關

2018年3月17日 06:34
編輯回答
離殤

通過父組件通過 props把數(shù)據(jù)傳給子組件,子組件改變
父組件每次傳一個對象給子組件, 對象之間引用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <style>

    </style>
    <script src="vue.js"></script>
    <script>
        window.onload=function(){
            new Vue({
                el:'#box',
                data:{
                    giveData:{
                        a:'我是父組件數(shù)據(jù)'
                    }
                },
                components:{
                    'child-com':{
                        props:['msg'],
                        template:'#child',
                        methods:{
                            change(){
                                //this.msg='被更改了'
                                this.msg.a='被改了';
                            }
                        }
                    }
                }
            });
        };
    </script>
</head>
<body>
    <template id="child">
        <div>
            <span>我是子組件</span>
            <input type="button" value="按鈕" @click="change">
            <strong>{{msg.a}}</strong>
        </div>
    </template>

    <div id="box">
        父級: ->{{giveData.a}}
        <br>
        <child-com :msg="giveData"></child-com>
    </div>
</body>
</html>
2017年5月31日 04:33