<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> <h3>父向子組件傳遞數據</h3> <!-- 加了冒號“”內表示一個表達式 --> <!-- 1.父組件傳遞name和count兩個數據 --> <!-- 4.父組件通過自定義事件監聽子組件傳遞的數據 --> <counter :name="'one'" :count="0" @change="handleIncrement"></counter> <counter :name="'two'" :count="0" @change="handleIncrement"></counter> <h4>子向父組件傳遞數據</h4> <div>父組件one+two=>{{total}}</div> </div> </body> <script type="text/javascript"> // 局部創建組件 let counter = { // 2.子組件用props接收 props: ['name', 'count'], data () { return { selfName: this.name, selfCount: this.count } }, template: '<div @click="handleClick">{{selfName}}---{{selfCount}}</div>', methods: { handleClick () { // vue單向數據流,不允許直接改變父組件穿過來的值, // this.count++ 報錯 // 需要先將數據保存到自己的組件里 this.selfCount++ // 3.子組件自定義事件向父組件傳遞數據 // 第二個參數可以為對象,數組,字符串 this.$emit("change", 1) } } } let vm = new Vue({ el: '#app', data: { total: 0, }, methods: { handleIncrement (value) { this.total += value } },
//注冊子組件 components: { counter } }) </script> </html>