vue零散记录之父子组件传值

本文介绍Vue.js中父组件与子组件间的通信方式,包括如何通过$emit实现子组件向父组件传递值,以及父组件如何接收这些值。同时,还探讨了输入框使用v-model时的注意事项。

1.input 使用了v-mode绑定值,不需要在写value;

2.子组件传值给父组件:$emit

父组件可获取子组件值:

举例:

父组件:parentServe.vue

<template>
  <div>
    <child-serve   @colorShow="ifshowColor"><!-- 这里是子组件传来的事件colorShow-->
    </child-serve>
  </div>
</template>

<script>
import childServev from "../components/childServe"

export default {
  methods:{
    showAdvice(advice){
      alert(advice)
    },
  },
  components:{
    child-serve:"childServe"
  },}
</script>

子组件:childServe

<template>
  <button @click="handleShowColor">
    我想弹窗传值给父组件呢
  </button>
</template>

<script>
  export default {
    data () {
      return {
        colorShow:false
    },
    methods:{

     handleShowColor (event) {

      event.stopPropagation();

      if (this.colorShow) {

        this.colorShow = false

      } else {

        this.colorShow = true

      }

       this.$emit("colorShow",this.colorShow);//colorShow是事件,this.colorShow是值

    },


  }
</script>

3.父组件传值给子组件的时候,是静态传值,如果子组件做操作,需要发起事件执行。

举例:-待补充

4.扩展知识:父子组件的加载顺序 - 按顺序执行,

如:先加载父组件,如过程发现子组件则执行子组件。最后输出结果。

 

 

Vue3中,父子组件主要通过`defineProps`和`defineEmits`实现,且这两个方法只在`<script setup>`中才能使用,不需要导入就会随着`<script setup>`被一同处理编译。 ### 父组件向子组件 父组件向子组件需要使用`defineProps`,其接收与`props`选项相同的。步骤如下: 1. 父组件通过自定义属性向子组件,示例代码如下: ```vue <template> <Subassembly :value="doc" /> </template> ``` 2. 子组件从`vue`中引入`defineProps`,并声明接收的,示例代码如下: ```vue <template> <h1>{{ props.value }}</h1> </template> <script setup> import { defineProps } from 'vue'; const props = defineProps(['value']); </script> ``` 此外,也可以在子组件中使用对象形式定义`props`并进行类型校验,示例如下: ```vue <template> <div> <h2>子组件</h2> <p>从父组件接收到的消息:{{ message }}</p> </div> </template> <script setup> defineProps({ message: { type: String, required: true, }, }); </script> ``` 还可以使用TypeScript增强类型提示,示例如下: ```typescript defineProps<{ message: string; count?: number }>() ``` ### 子组件向父组件 子组件向父组件使用`defineEmits`,其接收`emits`选项相同的。示例代码如下: ```vue <template> <button @click="sendDataToParent">向父组件</button> </template> <script setup> import { defineEmits } from 'vue'; const emits = defineEmits(['update']); const sendDataToParent = () => { emits('update', '这是子组件递的数据'); }; </script> ``` 父组件接收子组件递的数据: ```vue <template> <ChildComponent @update="handleUpdate" /> </template> <script setup> const handleUpdate = (value) => { console.log('接收到子组件的数据:', value); }; </script> ``` 同样可以使用TypeScript增强类型提示: ```typescript defineEmits<{ (e: 'update', value: string): void; (e: 'delete'): void }>() ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值