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
    }
  }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容