<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>
<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>
<p> {{ total }} </p>
<my-button4 @increment1= "incrementTotal1" ></my-button4>
<!--自定義方法increment1監聽子組件觸發情況-- >
<my-button4 @increment2= "incrementTotal2" ></my-button4>
<!--自定義方法increment2監聽子組件觸發情況-->
</div>
</template>
<script>
import myButton4 from '. /components/myButton4.vue'
export default {
data (){
return {
total : 0
}
} ,
methods :{
incrementTotal1 : function () { /*事件incrementTotal觸發*/
this . total += 1
} ,
incrementTotal2 : function () { /*事件incrementTota2觸發*/
this . total += 2
}
} ,
components :{ /*子組件的實例,要盡量放在最後,不然會出現一些不必要的問題*/
myButton4
}
}
</script>
<template>
<button @click= "incrementCounter" > {{counter}} </button>
<!--在子組件中創建一個按鈕,創建點擊事件-->
</template>
<script>
export default {
data (){
return {
counter : 0
}
},
methods : {
incrementCounter : function (){
this . counter += 1
this .$emit( 'increment1' )
/*觸發自定義事件increment1,也就是父組件中的incrementTotal1事件*/
this .$emit( ' increment2' )
/*觸發自定義事件increment2,也就是父組件中的incrementTotal2事件*/
/*這兩個事件一次只會觸發一個,為什麼呢?很簡單,因為每次只單擊一個按鈕*/
}
}
}
</script>