Warning: Undefined array key "HTTP_ACCEPT_LANGUAGE" in /www/wwwroot/www.bdysoft.com/usr/themes/Joe/public/tencent_protect.php on line 36

Deprecated: stripos(): Passing null to parameter #1 ($haystack) of type string is deprecated in /www/wwwroot/www.bdysoft.com/usr/themes/Joe/public/tencent_protect.php on line 36
vue3 父子组件之间的传值 - 凝梦

vue3 父子组件之间的传值

levis
2022-07-29 发布 / 正在检测是否收录...

第一种

使用 defineProps,defineEmits

父传子:parent.vue

<template>
    <div>
        <child :value="value" @add="childClick" :msg="msg" />
        <br />
    <div>{{msg1}}</div>
    <br />

        <button @click.stop="parentClick()">父组件按钮</button>
    </div>
</template>
<script setup lang="ts">
    /**
     * 引入必要的模块
     */
    import { ref } from 'vue'
    import  child  from './Child .vue'
    /**
     * 定义数据
     */
    const value = ref<number>(0);
    const msg = ref<string>('我是父组件传递过来的值啊~~');
    const msg1 = ref<string>('')

    /**
     * 定义方法
     */
     const parentClick = ()=> {
         value.value++
    }
  
 const childClick = (value)=>{
    msg1.value = value
  }

</script>

子组件:child.vue

<template>
   <div>
       <h1>{{ props.msg }}</h1>
       <h1>{{ props.value }}</h1>
       <button @click="onChildClick">子组件按钮</button>
   </div>
</template>
<script setup lang="ts">
    /**
    * 定义数据
    */
   const props = defineProps({ value: { type: Number },msg:{type:String} })
   const emit = defineEmits(['add'])

   /**
    * 定义方法
    */
   const onChildClick = ()=> {
       emit('add', '我是子组件传过来的值')
   }
</script>

第二种

父级组件向多层子组件传值 provide 和 inject

父级组件:

import { provide} from 'vue';
provide('parentMsg','我是父组件');

子组件:

import {inject} from 'vue';
const sonMsg = inject(parentMsg)

孙子组件

import {inject} from 'vue';
const grandsonMsg = inject(parentMsg)
© 版权声明
THE END
喜欢就支持一下吧
点赞 0 分享 收藏

评论 (0)

取消