vue-計算總和

前言

今天來做一個小練習。使用vue實現一個動態加載的計算總和。
效果圖如下:
在這裏插入圖片描述
當點擊前兩個 數字的時候,兩個數會加一,並把值賦給第三個值。
在這裏插入圖片描述


主要代碼

  1. 首先定義一個全局組件count
    Vue.component("count",{
        template:"<div @click='handClick'>{{number}}</div>",
        data:function(){
            return {
                number:0
            }
        },
        methods:{
            handClick:function(){
                // alert("dian")
                this.number++;
                // 子組件往父組件傳值 
                this.$emit("change")
            }
        }
    })

定義一個模板,裏面有一個點擊事件handClick,同時定義一個data,把number賦值0,最後子組件向父組件傳遞一個change。

2.父組件接收change

 <count @change="handleChange" ref="one"></count>
        +
        <count @change="handleChange" ref="two"></count>
        =
        <!-- 這個可不是count啊 -->
        <div >{{total}}</div>

ref代表接收子組件中的數據。

  1. 實現方法,把總數相加。
var vm = new Vue({
        el:"#root",
        data:{
            total:0

        },

        methods:{
            handleChange:function(){
                this.total = this.$refs.one.number+this.$refs.two.number
            }
        }
    })
發佈了70 篇原創文章 · 獲贊 63 · 訪問量 19萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章