总结
1 父组件通过子组件的 prop 属性, 将数据传送给子组件
(代码第三行的 cityName 就是子组件的属性)
2 子组件通过 $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>
来源: http://www.bubuko.com/infodetail-3614737.html