vue父組件調用子組件中的屬性和方法

接上篇,vue的父組件向子組件獲取值,若是父組件須要主動調用子組件中的屬性方法該如何實現?vue

獲取方法

一、 父組件中使用子組件的時候在給子組件定義一個ref屬性app

二、父組件能夠經過this.$refs.XXX,來操做子組件中的屬性和方法ide

子組件Sub1.vue

<template>
     <module :title="title" />
     <button :click="run()"></button>   
</template>
<script>  export  {
          name: "Sub1",
          data() {                 {
           //父組件能夠經過定義的ref調用到title
                  title: ''
             }
          }
          ,methods {
              run() {                   
                   console.log("sub1");              }
         }
    }</script>

父組件

<template>
     <!--這裏使用子組件的時候定義一個ref屬性1-->
     <sub1 ="sub"/>
     <button @click="callChild()"></button>
</template>
<script>export  {
      name: 'app',
      data() {              {
               title : 'test' 
           }
       },methods {
             callChild() {
            //這裏就能夠使用到子組件裏面的title屬性
                    console.log(this.$refs.title)
            //這樣能夠使用到子組件的方法
                    this.$ref.run();
             }
       }, components: {
          Sub1        }
}</script>

 

博主:測試生財測試

座右銘:專一測試與自動化,致力提升研發效能;經過測試精進完成原始積累,經過讀書理財奔向財務自由。this

csdn:https://blog.csdn.net/ccgshigao.net

博客園:https://www.cnblogs.com/qa-freeroad/component

51cto:https://blog.51cto.com/14900374blog

相關文章
相關標籤/搜索