子组件可以使用 $emit 触发父组件的自定义事件

子组件

<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>

父组件

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

  </div>
</template>

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

标签: none

添加新评论