vue父子組件傳參之ref


在vue中,傳參的常用的就父子組件傳參,兄弟組件傳參。今天我們說的是父子組件傳參中的一種方式$ref和ref

首先我們創建一個子組件 並給他添加一個number的值和綁定一個點擊事件@click='add()',每次點擊加1

  Vue.component('counter', {
            template: `<div @click='add'>{{number}}</div>`,
            data() {
                return {
                    number: 0
                }
            },
       methods: {
        add() {
          this.number++
        }
       },
        })

 

  並在我們父組件中調用它

<div id='app'>
   <div>
     <counter></counter>
     <counter></counter>
     <div>{{total}}</div>
   </div>
</div>


並且在子組件中使用change方法暴露出去

this.$emit('change')

 當子組件發生改變的時候像外暴露,我們可以打印出來看看

console.log(this.$emit('change')) 

很顯然我們得change方法是起作用了的     

<counter ref="one" @change='hand'></counter>
<counter ref="two" @change='hand'></counter>

我們再通過ref 傳入兩個參數,並且添加change事件

在父組件中寫入
  var app = new Vue({
    el: '#app',
    data:{
      total:0
    },
    methods:{
      hand(){
        this.total = this.$refs.one.number+ this.$refs.two.number
      }
    }
  })

這樣我們就完成了父組件的傳值

 

完整代碼如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src='vue.js'></script>
</head>
<body>
    <div id='app'>
        <counter ref='one' @change='hand'></counter>
        <counter ref='two' @change='hand'></counter>
        <div>{{total}}</div>
    </div>

    <script>
        Vue.component('counter',{
            template:`<div @click='add'>{{number}}</div>`,
            data() {
                return {
                    number:0
                }
            },
            methods: {
                add() {
                    this.number++
                    this.$emit('change')
                    console.log(this.$emit('change'))
                }
            },
        })
        var app = new Vue({
            el:'#app',
            data:{
                total:0
            },
            methods:{
                hand () {
                    this.total = this.$refs.one.number+this.$refs.two.number
                }
            }

        })
    </script>
</body>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM