父子组件 - 父组件向子组件传递数据

父组件
在父组件引入的子组件中定义属性:imgs="imgData"

<template>
  <div class="container">
    <div
      class="banner"
      @click="handleBannerClick"
    >
      <img
        src="/static/imgs/banner-1.jpg"
        alt=""
      >
      <div class="backtrack"></div>
    </div>
    <common-gallary :imgs="imgData" v-show="showGallary" @close="handleGallaryClose"></common-gallary>
  </div>
</template>

<script>
import CommonGallary from '@common/Gallary'
export default {
  name: 'DetailBanner',
  components: {
    CommonGallary
  },
  data () {
    return {
      showGallary: false,
      imgData: ['/static/imgs/goods-1.jpg', '/static/imgs/goods-2.jpg', '/static/imgs/goods-3.jpg']
    }
  }
}
</script>

子组件
在子组件中使用props进行接收父组件传来的值

<template>
  <div class="container">
    <div class="wrapper">
      <swiper :options="swiperOptions">
        <swiper-slide
          v-for="(item,index) in imgs"
          :key="index"
        >
          <img :src="item">
        </swiper-slide>
        <div
          class="swiper-pagination"
          slot="pagination"
        ></div>
      </swiper>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Gallary',
  props: {
    imgs: {
      type: Array,
      default () {
        return []
      }
    }
  }
}
</script>

props验证
可以为组件的 props 指定验证规格。如果传入的数据不符合规格,Vue会发出警告。当组件给其他人使用时,这很有用
要指定验证规格,需要用对象的形式,而不能用字符串数组

props: {
    // 基础类型检测 (`null` 意思是任何类型都可以)
    propA: Number,
    // 多种类型
    propB: [String, Number],
    // 必传且是字符串
    propC: {
      type: String,
      required: true
    },
    // 数字,有默认值
    propD: {
      type: Number,
      default: 100
    },
    // 数组/对象的默认值应当由一个工厂函数返回
    propE: {
      type: Object,
      default: function () {
        return { message: 'hello' }
      }
    },
    // 自定义验证函数
    propF: {
      validator: function (value) {
        return value > 10
      }
    }
  }
Last modification:April 25th, 2019 at 05:30 pm
如果觉得我的文章对你有用,请随意赞赏

Leave a Comment