父子傳值!代碼詳解

父傳子:

<body>
    <div id='app'>
        <songname title="我是父組件傳來的"> </songname>
        <songname></songname>
        <songname :title="title"></songname>
    </div>
    <template id="login">
        <div>
            登錄組件
            父組件傳值:{
   
   {
   
   title}}
        </div>
    </template>
    <script>
        // 定義組件
        Vue.component("songname", {
   
      //組件名
            template: "#login",   //組件id
            props: {
   
   
                // 1、 指定數據類型 title:string
                // 2、指定多種數據類型
                // title: [String, Number],
                // 3.指定默認數據
                title: {
   
   
                    type: String,
                    default: "課程標題",
                },
            }
        })

    </script>
    <script>
        const vm = new Vue({
   
   
            el: '#app',
            data: {
   
   
                title: "我是父組件傳來的動態屬性綁定"
            }
        })
    </script>

子傳父:

<body>
    <!-- 父 -->
    <div id='app'>
        <!-- 子 -->
        <sonname @father="fatherchange"></sonname>
        {
   
   {
   
   sondata}}
    </div>
    <template id="login">
        <div>
            登錄組件
            父組件傳值:{
   
   {
   
   title}}
            <button @click="addDataTofather"> 點我幹大事</button>

        </div>
    </template>
    <script>
        Vue.component("sonname", {
   
   
            template: "#login",
            props: {
   
   
                // 1.指定數據類型
                // title:String
                // 2指定多種數據類型
                // title:[String,Number]
                // 3指定默認數據
                // title:{
   
   
                //     type:String,
                //     default:"課程標題"
                // },
                title: {
   
   
                    type: [String, Number],
                    default: "課程標題"
                }

            },
            methods: {
   
   
                addDataTofather() {
   
   

                    this.$emit("father", "傳過來的子組件數據")
                }
            },
        })

    </script>
    <script>
        const vm = new Vue({
   
   
            el: '#app',
            data: {
   
   
                title: "俺是父組件傳來的動態屬性綁定",
                sondata: ""
            },
            methods: {
   
   
                fatherchange(data) {
   
   
                    console.log(data);
                    this.sondata = data
                }
            },
        })
    </script>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章