|
1.在Vue3中,子组件可以通过props接收父组件传递的值,也可以通过$emit方法向父组件发送事件。具体操作如下:
父组件传递值给子组件:
父组件中使用子组件时,可以在子组件标签上使用属性绑定的方式,将父组件中的数据传递给子组件:
- <template>
- <div>
- <ChildComponent :msg="parentMsg" />
- </div>
- </template>
- <script>
- import ChildComponent from './ChildComponent.vue'
- export default {
- name: 'ParentComponent',
- components: { ChildComponent },
- data() {
- return {
- parentMsg: 'Hello from parent!'
- }
- }
- }
- </script>
复制代码
子组件中通过props接收父组件传递的值:
- <template>
- <div>
- {{ msg }}
- </div>
- </template>
- <script>
- export default {
- name: 'ChildComponent',
- props: {
- msg: String
- }
- }
- </script>
复制代码
2.子组件向父组件发送事件:
子组件中通过$emit方法触发一个自定义事件,父组件通过在子组件标签上使用v-on绑定自定义事件的方式,监听子组件触发的事件并处理:
- <template>
- <div>
- <button @click="sendMsg">发送消息到父组件</button>
- </div>
- </template>
- <script>
- export default {
- name: 'ChildComponent',
- methods: {
- sendMsg() {
- this.$emit('send-msg', 'Hello from child!')
- }
- }
- }
- </script>
复制代码
父组件中监听子组件触发的事件,并处理:
- <template>
- <div>
- <ChildComponent @send-msg="handleMsg" />
- </div>
- </template>
- <script>
- import ChildComponent from './ChildComponent.vue'
- export default {
- name: 'ParentComponent',
- components: { ChildComponent },
- methods: {
- handleMsg(msg) {
- console.log(msg)
- }
- }
- }
- </script>
复制代码
|
|