父组件:
<template>
<div class="father">
<div class="father-self">
<h1>我是父组件</h1>
<p>{{ fatherMsg }}</p>
<h2>{{ userName }}</h2>
<h1>{{ info }}</h1>
</div>
<!-- 3. 使用子组件 -->
<Son @SonToFather="fn" :msg="msg" :userName="userName" :message="message"></Son>
</div>
</template>
<script>
// 1. 引入组件
import Son from '@/components/Son.vue'
export default {
components: { // 2. 注册组件
Son
},
data() {
return {
fatherMsg: '我是父组件自己的数据',
msg: '要传给儿子的数据...',
userName: '李寻欢',
message: '我是要传入的数据哈哈哈哈哈',
info: ''
}
},
methods: {
fn(data) {
console.log(data)
this.info = data;
}
}
}
</script>
子组件:
<template>
<div class="son">
<h3>我是儿子组件</h3>
<p>{{ sonMsg }}</p>
<h3>来自父的数据: 1. {{ msg }} / 2. {{ userName }}</h3>
<h3>3. {{ message }}</h3>
<!-- 绑定事件 -->
<button @click="sendMsg">传给爸爸</button>
</div>
</template>
<script>
// 引入组件
import Sz from '@/components/Sz.vue'
export default {
components: {
Sz
},
// props数组的写法
// props: ['msg', 'userName', 'message'],
// props对象的写法:
props: {
msg: {
type: String,
default: () => '哈哈哈'
},
userName: {
type: String,
default: () => '呵呵呵'
},
message: {
type: String,
default: () => '嘿嘿嘿'
}
},
data() {
return {
sonMsg: '我是子组件自己的数据',
info: '我是儿子的数据,我要传给爸爸!'
}
},
methods: {
sendMsg() {
// 把数据传给父组件
this.$emit('SonToFather', this.info)
}
}
}
</script>
<style lang="less">
.son {
border: 1px solid red;
margin-top: 30px;
}
</style>