转自:https://blog.csdn.net/m0_56388720/article/details/123067654
props 和 $emit
-
子组件向父组件传值,通过$emit 事件向父组件发送消息,将自己的数据传递给父组件。
-
props 可以在组件上注册一些自定义属性。父组件通过绑定该属性来向子组件传入数据,子组件通过 props 属性获取对应数据。
示例
父组件
// parent.vue
<template>
<div>
<p>childMessage: {{childMessage}}</p>
<children :sendmessage='childMessage' @showMsg="updataMsg"></children>
</div>
</template>
import children from '/*...*/'
export default{
data () {
return {
childMessage: '父组件给子组件传值'
}
},
methods: {
updataMsg(message) {
this.childMessage = message
console.log(this.childMessage)
}
},
components: {
children
}
}
子组件
// children.vue
<template>
<div>
// 通过按钮点击事件将子组件的值传给父组件
<button @click="sendtoParent">Click this Button</button>
</div>
</template>
<script>
export default {
props: ['sendmessage'],
methods: {
sendtoParent() {
//$emit括号里的第一个参数为自定义事件
this.$emit('showMsg','子组件通过$emit给父组件传值')
}
}
}
</script>
更多精彩内容:各种AI课程、技能课程、黑科技软件、网站小程序源码、副业小项目、PPT模板等精品素材、电商课程、推广引流课程等,尽在 天边资源网 。