直接上代码。
<template>
// 子组件
<div>
{{msg}}---child子组件里msg信息
<hr>
{{child}}--props接收到父组件的信息
<hr>
<input @click="sendMsg" type="button" value="给父组件传递值">
</div>
</template>
<script>
export default {
data() {
return {
msg: '我是一个child组件',
//将num传递给父组件
num: 0,
}
},
props: {
child: {
type: String
}
},
methods: {
// 用来传递的函数方法
sendMsg() {
// get是父组件指定的传数据绑定的函数,this.num:子组件给父组件传递的数据
this.$emit('get', this.num)
}
},
}
</script>
<template>
<div>
// 父组件
<Child :child="childd" @get="getNum"></Child>
<div>父组件--{{num}}</div>
</div>
</template>
<script>
import Child from '@/components/child'
export default {
name: 'app',
data() {
return {
num: 100,
}
},
methods: {
getNum(val) {
// 将子组件获取到的num值赋值给父组件的变量
this.num = val
console.log(val, '父组件接收到的值val');
}
},
components: {
Child,
}
}
</script>