vue 父組件調用子組件數據


<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
    </head>
    <body>
        <div class="" id="myVue">
            <my-component>
            </my-component>
        </div>
        
        <!--子組件-->
        <template id="child"  >
            <div id="">
                <button v-on:click='senddata'>傳數據到父組件</button>
            </div>
        </template>
        <!--父組件-->
        <template id="father">
            <div>
                <h3>我是:{{str}}</h3>
                <mycomponent-child  v-on:showstrr="shouchilddata"></mycomponent-child>
            </div>
        </template>
    </body>
    <script type="text/javascript" charset="utf-8">
        /*子組件傳數據到父組件
         * 1:子組件加事件eg:v-on:click='senddata'
         * 2:senddata方法中用this.$emit設置監聽事件eg:this.$emit('showstrr',this.strr);  
         *    showname是時間名,this.strr傳入父組件的數據
           3.父組件監聽子組件觸發的showname事件,然后調用shouchilddata方法獲取子組件數據
         * */
        //注vue使用$emit時傳入的事件名稱只能使用小寫,不能使用大寫的駝峰規則命名
        /*子組件*/
        var child={
            template:"#child",
            data:function(){
                return{
                    strr:"我是子組件數據"
                }
            },
            methods:{
                senddata:function(){
                     this.$emit('showstrr',this.strr);
                }
            }
            
        }
        /*父組件*/
        var father={
            template:"#father",
            data:function(){
                return{
                    str:"我是父組件數據"
                }
            },
            methods:{
                shouchilddata:function(data){
                    alert("父組件:"+data)
                },
            },
            components:{
                "mycomponentChild":child
            }
        }
        vm=new Vue({
            //el:"#myVue",
            components:{
                "myComponent":father
            }
        }).$mount('#myVue');
        
    </script>
</html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM