vue-父子組件傳值傳方法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--<script src="https://cdn.bootcss.com/vue/2.5.22/vue.min.js"></script>-->
    <script src="lib/vue.min.js"></script>
    <link rel="stylesheet" href="lib/bootstrap.min.css"/>
    <script src="lib/moment-with-locales.min.js"></script>
</head>
<body>
    <div id="app">
        <!--父組件可以在引用子組件的時候通過屬性綁定的形式向子組件傳值,同時需要把父組件傳過來的數據在子組件的props中定義一下-->
        <com1 :msg1="msg"></com1>
        <button class="btn btn-danger" @click="clean">重置</button>
        <button class="btn btn-info" @click="show('')">父組件按鈕</button>
        <div style="width: 100px;height: 100px;background-color: orangered">{{showMsg}}</div>
         <!--傳遞方法-->
        <com2 v-on:func="show"></com2>
        <div style="width: 100px;height: 100px;background-color:greenyellow">{{msgFromSon}}</div>
    </div>
    <template id="temp2">
        <div>
            <h1>這是子組件</h1>
            <button class="btn btn-info" @click="childShow">子組件按鈕</button>
        </div>
    </template>
<script>
    var com2 = {
        template:'#temp2',
        data:function(){
            return {
                sonMsg:{name:'小頭兒子',age:18}
            }
        },
        methods:{
            childShow:function(){
                //emit代表觸發調用的意思   this代表該組件
                this.$emit('func',this.sonMsg)
            }
        }
    }
    var app = new Vue({
        el:"#app",
        data:function(){
            //data中的數據都是子組件私有的,可讀可寫
            return {
                msg:'父組件的數據',//vue相當於一個父組件,
                showMsg:'',
                msgFromSon:null
            }
        },
        methods:{
            show:function(message){
                console.log(typeof(message));
                if(typeof(message)=='object'){
                    message = JSON.stringify(message)
                }
                this.showMsg = "我被觸發了"+message
                this.msgFromSon = message
            },
            clean:function(){
                this.showMsg = ""
            }
        },
        components:{
            //子組件默認無法訪問父組件中的數據
            'com1':{
                 template:'<h3>子組件引用父組件的數據--{{msg1}}</h3>' ,
                 //注意:props中的數據都是通過父組件傳遞過來的,props中的數據只讀
                 props:['msg1'],//把父組件傳過來的數據在props中定義一下
                 data:function(){
                     return {
                         comMsg:'子組件私有數據'
                     }
                 }
             },
             com2//相當於'com2':com2
        }
    });
</script>
</body>
</html>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章