vue父組件向子組件傳值

簡介

vue中組件與組件的關係存在兩類:父子組件與非父子組件。html

以下圖所示,三個組件中就包含了父子組件與非父子組件兩種狀況,這裏組件之間的交互主要由值傳遞和事件觸發調用兩種方式,這裏先分享下父組件向子組件值傳遞。vue

方式

父組件能夠向子組件傳遞的值有三種類型數組

  1. 屬性變量或者純文本
  2. 函數名
  3. 父組件自身實例(this)

例子

假設有兩個組件App.vue和Sub1.vue,其中App.vue爲父組件,Sub1.vue爲子組件。app

父組件App.vue

<template>
     <!--父組件傳遞titile,run,home給子組件sub1-->
     <!--其中title爲屬性,run爲方法,this爲父組件實例的指針-->
     <sub1 :title="title" :run="run" :home="this"  ref="deleteConfirm"/>
</template>
<script>
//導入子組件
import Sub1 from './Sub1.vue' 
export default {
      name: 'app',
      data() {
             return {
               title : 'test' 
           }
       },methods {
             run() {
                    console.log('parent')
             }
       }, components: {
          Sub1 //掛載子組件Sub1
       }
}
</script>

子組件Sub1.vue

<template>
     <!--子組件接收父組件傳過來的title-->
     <module :title="title" : ref="deleteConfirm"/>
     <!--這裏點擊button能夠調用父組件的run方法-->
     <button :click="run()"></button>
     <!--runParent內部經過父組件的this指針調用父組件的屬性和方法-->
     <button :click="runParent()"></button>
</template>
<script>
  export default {
          name: "Sub1",
          data() {
                return {
                  title: ''
             }
          },
          //1.第一種方法,用數組的方式接收父組件的傳值:title,run,home
          props: ['title','run','home'],
         ,methods {
              runParent() {
                   //能夠經過父組件實例this.home直接調用父組件中的方法。
                   console.log(this.home.title);
             this.home.run();
              }
         }
    }
</script>

prop接收參數

prop有兩種接收父組件傳遞的參數語法。ide

第一種就是上面的props: ['title','run','home'],這種數組方式函數

第二種:咱們也能夠在傳遞值的時候對prop進行校驗。測試

常見的類型:this

  • String
  • Number
  • Boolean
  • Array
  • Object
  • Date
  • Function
  • Symbol

上面的Props能夠改爲以下url

   props: {
        title: {  //接收父組件傳遞過來的title
             type: String,
             default() {
                  //若是父組件沒有傳遞title變量,則使用default()獲取一個默認值
                  return this.$t('commons.title')
            }
        },
        run: { //接收父組件傳遞過來的run方法,
             type: Function,
             default: function () {
                  console.log('hello')
             }
        },
        home: { //接收父組件自己
             type: Object,
        }
  },


博主:測試生財spa

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

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

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

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

相關文章
相關標籤/搜索