<template> <div class="train-city"> <h3>父組件傳給子組件的toCity:{{sendData}}</h3> <br/><button @click='select(`大連`)'>點擊此處將‘大連’發射給父組件</button> </div> </template> <script> export default { name:'trainCity', props:['sendData'], // 用來接收父組件傳給子組件的數據 methods:{ select(val) { let data = { cityname: val }; this.$emit('showCityName',data);//select事件觸發後,自動觸發showCityName事件 } } } </script>
<template> <div> <div>父組件的toCity{{toCity}}</div> <train-city @showCityName="updateCity" :sendData="toCity"></train-city> </div> <template> <script> import TrainCity from "./train-city"; export default { name:'index', components: {TrainCity}, data () { return { toCity:"北京" } }, methods:{ updateCity(data){//觸發子組件城市選擇-選擇城市的事件 this.toCity = data.cityname;//改變了父組件的值 console.log('toCity:'+this.toCity) } } } </script>