父子組件之間的訪問

父訪問子$children $refs

  • $children
cpn: {
          template: '#cpn',
          data(){
            return{
              name:'黃開然'
            }
          },
          methods: {
            showMessage() {
              console.log('showMessage')
            }
          }
        }
      }

如何在父組件中調用showMessage()?

<div id="app">
    <cpn></cpn>
    <button @click="btnClick">button</button>
</div>
  
var vm = new Vue({
      el: '#app',
      data: {},
      methods: {
        btnClick() {
          console.log(this.$children)
          for(let c of this.$children){
            console.log(c.name)
            c.showMessage()
          }
        }
      }
  • refs
默認是個空的對象

一個類似id的標識
使用:

<cpn ref="aaa"></cpn>
methods: {
        btnClick() {
          console.log(this.$refs.aaa.name)
        }
      },

子訪問父 $parent $root

不常用

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章