其他分享
首页 > 其他分享> > 二.Vue2.5开发去哪儿网app城市列表页④——字母表随下拉而变换(兄弟组件间的联动)

二.Vue2.5开发去哪儿网app城市列表页④——字母表随下拉而变换(兄弟组件间的联动)

作者:互联网

当我们处理兄弟组件时,可以让一个组件的数据给父组件,然后让父组件的这个数据传递给另一个组件

设置Alphabet子组件,当其一个字母被点击时向外触发一个change事件,并携带它的文本内容

<template>
  <ul class="list">
    <li class="item" v-for="(item, key) of cities" :key="key" @click="handleLetterClick">{{key}}</li>
  </ul>
</template>

<script>
export default {
  name: 'CityAlphabet',
  props: {
    cities: Object
  },
  methods: {
    handleLetterClick (e) {
      this.$emit('change', e.target.innerText)
    }
  }
}
</script>

父组件City监听这个change事件,监听到这个事件后,触发handleLetterChange事件,并接收这个事件的参数,然后把这个参数以单向绑定的方式传递给子组件List

<template>
  <div>
    <city-header></city-header>
    <city-search></city-search>
    <city-list :hotCities="hotCities" :cities="cities" :letter="letter"></city-list>
    <city-alphabet :cities="cities" @change="handleLetterChange"></city-alphabet>
  </div>
</template>

<script>
import CityHeader from './components/Header'
import CitySearch from './components/Search'
import CityList from './components/List'
import CityAlphabet from './components/Alphabet'
import axios from 'axios'
export default {
  name: 'City',
  components: {
    CityHeader,
    CitySearch,
    CityList,
    CityAlphabet
  },
  data () {
    return {
      hotCities: [],
      cities: {},
      letter: ''
    }
  },
  methods: {
    getCityInfo () {
      axios.get('/api/city.json')
        .then(this.getCityInfoSuss)
    },
    getCityInfoSuss (res) {
      res = res.data
      if (res.ret && res.data) {
        const data = res.data
        this.hotCities = data.hotCities
        this.cities = data.cities
      }
    },
    handleLetterChange (letter) {
      this.letter = letter
    }
  },
  mounted () {
    this.getCityInfo()
  }
}
</script>

 

标签:cities,随下,res,app,components,组件,import,Vue2.5,data
来源: https://blog.csdn.net/Vansal/article/details/87905661