Vue学习笔记-父子通信案例

 1 <div id="app">
 2     <cpn :number1="num1"
 3          :number2="num2"
 4          @num1change="numchange1"
 5          @num2change="numchange2"
 6     >
 7 
 8     </cpn>
 9 </div>
10 
11 
12 <template id="cpn">
13     <div>
14         <!--1.子组件里的双向绑定只能用子组件data里面的值-->
15 
16         <!--<h2>{{number1}}</h2>-->
17         <!--&lt;!&ndash;props单向数据流,不允许子组件直接改变props里面的值&ndash;&gt;-->
18         <!--&lt;!&ndash;<input type="text" v-model="number1">&ndash;&gt;-->
19         <!--&lt;!&ndash;可以用子组件data里面的数据实现双向绑定&ndash;&gt;-->
20         <!--<input type="text" v-model="dnumber1">-->
21         <!--<h2>{{number2}}</h2>-->
22         <!--<input type="text" v-model="dnumber2">-->
23 
24 
25         <!--2.子组件的值改变时传到父组件改变父组件的值-->
26         <!--v-model的本质是v-bind绑定一个value属性,v-on指令给当前元素绑定input事件-->
27 
28         <h2>{{number1}}</h2>
29         <input type="text" :value="dnumber1" @:input="num1Input">
30         <h2>{{number2}}</h2>
31         <input type="text" :value="dnumber2" @:input="num2Input">
32     </div>
33 </template>
34 
35 </body>
36 <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
37 <script>
38     const cpn = {
39         template: '#cpn',
40         props: { //props单向数据流,父组件传递到子组件的值不允许子组件直接改变
41             number1: Number,
42             number2: Number
43         },
44         data() { //想要修改props里的值可以在data里面保存一份,然后修改
45             return {
46                 dnumber1: this.number1,
47                 dnumber2: this.number2
48             }
49         },
50         methods: {
51             num1Input (event) {
52                 this.dnumber1 = event.target.value
53                 this.$emit('num1change',this.dnumber1)
54             },
55             num2Input (event) {
56                 this.dnumber2 = event.target.value
57                 this.$emit('num2change',this.dnumber2)
58             }
59         }
60     }
61     const app = new Vue ({
62         el: '#app',
63         data: {
64             num1: 1,
65             num2: 2
66         },
67         components: {
68                 cpn
69         },
70         methods: {
71             numchange1 (value) {
72                 this.num1 = parseInt(value)
73             },
74             numchange2 (value) {
75                 this.num2 = parseInt(value)
76             }
77         }
78     })
79 </script>

 

posted @ 2019-11-21 16:19  leahtao  阅读(116)  评论(0编辑  收藏  举报