当前位置:主页 > 网页前端 > vue >

vue点击自增和求和的实例代码

时间:2021-01-17 14:06:45 | 栏目:vue | 点击:

如下所示:

<!DOCTYPE html>
<html>
 <head>
 <meta charset="UTF-8">
 <title>ref</title>
 <script type="text/javascript" src="js/vue.js" ></script>
 </head>
 <body>
 <div id="root">
  <counter></counter>
  <counter></counter>
 </div>
 <script>
  Vue.component('counter',{
  template:'<div @click="handleClick">{{number}}</div>',
  data:function () {
   return {
   number:0
   }
  },
  methods:{
   handleClick:function () {
   this.number++
   }
  }
  
  })
  var vm = new Vue({
  el:'#root',
  
  })
 </script>
 </body>
</html>

求和

<!DOCTYPE html>
<html>
 <head>
 <meta charset="UTF-8">
 <title>ref</title>
 <script type="text/javascript" src="js/vue.js" ></script>
 </head>
 <body>
 <div id="root">
  <counter ref="one" @change="handleChange"></counter><!--2.父组件监听-->
  <counter ref="two" @change="handleChange"></counter>
  
  <div >{{total}}</div><!--//子组件向父组件传值--><!--求和-->
 </div>
 <script>
  Vue.component('counter',{
  template:'<div @click="handleClick">{{number}}</div>',
  data:function () {
   return {
   number:0
   }
  },
  methods:{
   handleClick:function () {
   this.number++   //点击数字自增一
   this.$emit('change')//1.子组件向外触发change函数,父组件<counter>监听
   }
  }
  
  })
  var vm = new Vue({
  el:'#root',
  data:{
   total:0
  },
//  3.在父组件里定义handleChange方法
  methods:{
   handleChange:function () {
   this.total=this.$refs.one.number + this.$refs.two.number
   console.log(this.$refs.one.number)
   console.log(this.$refs.two.number)
  }
  }
  })
//  4.在counter里定义ref="one"
//  5.在vue里定义 console.log(this.$refs.one) 再通过number获取自增的值
//     6.通过total获取两数之和
 </script>
 </body>
</html>

您可能感兴趣的文章:

相关文章