Vue父子组件之间的传值

1、父组件向子组件传值

父组件中
<template>
  <div>
    <home-swiper :swiperList='swiperList'></home-swiper>
  </div>
</template>
<script>
import HomeSwiper from './components/Swiper'
export default{
  name: 'Home',
  components: {
    HomeSwiper
  },
  data () {
    return {
      swiperList: []
    },
  computed: {
    ...mapState({
      currentCity: 'city'
    })
  },
  methods: {
    getHomeInfo () {
      axios.get('/api/index.json?city=' + this.currentCity)
        .then(this.getHomeInfoSucc)
    },
    getHomeInfoSucc (res) {
      res = res.data
      if (res.ret && res.data) {
        const data = res.data
        this.city = data.city
        this.swiperList = data.swiperList
      }
    }
  },
  mounted () {
    this.lastCity = this.currentCity
    this.getHomeInfo()
  },
  activated () {
    if (this.lastCity !== this.currentCity) {
      this.lastCity = this.currentCity
      this.getHomeInfo()
    }
  }
  
子组件中
<template>
  <div class="wrapper">
  <swiper :options="swiperOption" v-if="showSwiper">
    <!-- slides -->
    <swiper-slide v-for='item of swiperList' :key='item.id'>
      <img
        class="swiper-img"
        :src="item.imgUrl"
      />
    </swiper-slide>
    <!-- Optional controls -->
    <div class="swiper-pagination"  slot="pagination"></div>
  </swiper>
  </div>
</template>
<script type="text/javascript">
export default{
  name: 'HomeSwiper',
  props: {
    swiperList: Array
  },
  data () {
    return {
      swiperOption: {
        pagination: '.swiper-pagination',
        loop: true,
        speed: 400,
        autoplay: 2000
      }
    }
  },
  computed: {
    showSwiper () {
      return this.swiperList.length
    }
  }
}
</script>

2、子组件向父组件传值

子组件中
<template>
  <div class="container" @click="handleGallaryClick"> </div>
</template>

<script>
  methods: {
    handleGallaryClick () {
      this.$emit('close')
    }
  }
</script>
父组件中
<template>
  <div>
   <common-gallary :imgs="gallaryImgs" v-show='showGallay' @close="handleGallaryClose"></common-gallary>
  </div>
</template>

<script type="text/javascript">
import CommonGallary from 'common/gallary/Gallary'
export default{
  name: 'DetailBanner',
  props: {
    gallaryImgs: Array
  },
  data () {
    return {
      showGallay: false
    }
  },
  components: {
    CommonGallary
  },
  methods: {
    handleGallaryClose () {
      this.showGallay = false
    }
  }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容