利用组件实现求任意两数之和

 1 <!doctype html>
 2 <html>
 3 <head>
 4 <meta charset="utf-8">
 5 <title>获取子组件的数据,然后求和</title>
 6 <!--适应移动端-->
 7 <meta name="viewport" content="width=device-width, initial-scale=1">
12 <!--引用Vue.js-->
13 <script src="https://unpkg.com/vue/dist/vue.js"></script>
14 </head>
15 
16 <body>
17     <div id="myVue">
18         <myput v-on:increment="increaTatal" ref="myput1"></myput>
19         <myput v-on:increment="increaTatal" ref="myput2"></myput>
20         两数之和是:{{sum}}
21     </div>
22     <script type="text/javascript">
23         Vue.component('myput',{
24             template:'<input @change="increaHandler" value="0">',
25             data:function(){
26                 return {
27                     counter:0
28                 }
29             },
30             methods:{
31                 increaHandler:function (event){
32                   this.counter=event.target.value
33                 
34                     //这里要用双引号
35                     this.$emit("increment")
36                 }
37             }
38         })
39         new Vue({
40             el:'#myVue',
41             data:{
42                 sum:0
43             },
44             methods:{
45                 increaTatal:function (){
46                   this.sum=parseInt(this.$refs.myput1.counter)+parseInt(this.$refs.myput2.counter)
47                 }
48             }
49             
50         })
51         
52     </script>
53 
54 </body>
55 </html>

猜你喜欢

转载自www.cnblogs.com/blogsky-520/p/12742089.html