总结
① 父组件通过子组件的prop属性,将数据传送给子组件
(代码第三行的cityName就是子组件的属性)
② 子组件通过$emit监测父组件中的事件(代码最后一行)
父组件
<template>
<div id="father">
<son @btnClick="handleClick" :cityName="msg"></son>
</div>
</template>
<script>
import son from './components/son'
export default {
el: '#father',
data() {
return {
msg: '' // 要传给子组件的数据
}
},
methods: {
handleClick() {
this.msg = '北京' // 点击按钮时触发函数,显示hello
}
},
components: {
'son': son
}
}
</script>
子组件
<template>
<div>
<button @click="sendCity">点击</button>
<h1>父组件传过来的数据是:{{cityName}}</h1>
</div>
</template>
<script>
export default {
props: ['cityName'], // 子组件的自定义属性
methods: {
sendCity() {
this.$emit('btnClick'); // 使用$emit()监测btnClick事件
}
}
}
</script>