<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>ref</title> <script type="text/javascript" src="https://www.jb51.net/js/vue.js" ></script> </head> <body> <div> <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="https://www.jb51.net/js/vue.js" ></script> </head> <body> <div> <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>
以上这篇vue点击自增和求和的实例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
您可能感兴趣的文章: