本文实例为大家分享了vue实现组件值的累加的具体代码,供大家参考,具体内容如下
css代码:
<style> ? ? ? ? #myLit{ ? ? ? ? ? ? border: 1px solid red; ? ? ? ? ? ? width: 100px; ? ? ? ? ? ? float: left; ? ? ? ? ? ? margin-right: 20px; ? ? ? ? } ? ? ? ? //定义不同的颜色类 ? ? ? ? .red{ ? ? ? ? ? ? color: red; ? ? ? ? } ? ? ? ? .olive{ ? ? ? ? ? ? color: olive; ? ? ? ? } ? ? ? ? .blue{ ? ? ? ? ? ? color: blue; ? ? ? ? } </style>
html代码:
<div id="myBtn"> ? ? ? ? <span>点赞总数{{sum}}</span> ? ? ? ? //点赞总数递增的按钮,隐藏该按钮 ? ? ? ? <button @click="clickSum" id="sumZan">点赞</button> ? ? ? ? <p></p> ? ? ? ?<!-- ? ? ? ? ? ? myfun是自定义函数,命名不能出现大写字母,因为事件监听器在 DOM 模板中会被自动转换为全小写 ? ? ? ? ? ? color是自定义属性,改变字体颜色 ? ? ? ? ? ? msg是自定义按钮值 ? ? --> ? ? ? ??? ? <ui-btn @myfun="clickSum" msg="组长的点赞"></ui-btn> ? ??? ??? ? <ui-btn @myfun="clickSum" color="olive" msg="小小的点赞"></ui-btn> ? ??? ??? ? <ui-btn @myfun="clickSum" color="blue"></ui-btn> ? ? </div>
js代码:
computed区别于method最重要的两点
computed是属性调用,而methods是函数调用
computed带有缓存功能,而methods不是
<script src="dist/vue.min.js"></script> <script> ?? ?// 组件 ? ? Vue.component("ui-btn",{/*ui-btn是自定义标签名*/ ? ? ? ? template: ?` ? ? ? ? ? ? // html结构 ? ? ? ? ? ? <div id="myLit" :class="color"> ? ? ? ? ? ? ? ? <p>点赞次数{{count}}</p> ? ? ? ? ? ? ? ? <button @click="countFun">{{msg}}</button> ? ? ? ? ? ? </div> ? ? ? ? `, ? ? ? ? data:function () { ? ? ? ? ? ? return { ? ? ? ? ? ? ? ? // 组件里所要用到的数据 ? ? ? ? ? ? ? ? count:0, ? ? ? ? ? ? } ? ? ? ? }, ? ? ? ? methods:{ ? ? ? ? ? ? countFun(){ ? ? ? ? ? ? ? ? this.count++; ? ? ? ? ? ? ? ? // 模拟触发sumCount函数,这里实际上就是去触发自定义事件 ? ? ? ? ? ? ? ? this.$emit("myfun") ? ? ? ? ? ? } ? ? ? ? }, ? ? ? ? props:{ ? ? ? ? ? ? color:{ ? ? ? ? ? ? ? ? type:String, //类型为字符串,若非字符串会自动转换 ? ? ? ? ? ? ? ? default:"red" //默认值 ? ? ? ? ? ? }, ? ? ? ? ? ? msg:{ ? ? ? ? ? ? ? ? type:String, ? ? ? ? ? ? ? ? default:"我的点赞" ? ? ? ? ? ? } ? ? ? ? } ? ? }) ? ? // 实例 ? ? var appBtn=new Vue({ ? ? ? ? el:"#myBtn",//作用域,生命周期 ? ? ? ? data:{//数据 ? ? ? ? ? ? sum:0 ? ? ? ? }, ? ? ? ? computed:{//计算属性 ?? ??? ??? ??? ? ? ??? ??? ? }, ? ? ? ? methods:{ ? ? ? ? ? ? clickSum(){ ? ? ? ? ? ? ? ? this.sum++ ? ? ? ? ? ? } ? ? ? ? } ? ? }) </script>
页面效果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did121281