zoukankan      html  css  js  c++  java
  • vue3 父子组件之间的传值

    第一种:需要用到  defineProps,defineEmits;用法其实跟vue2.x基本上还是一样的

    父传子: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)
     
  • 相关阅读:
    php的错误处理机制
    php的自动加载函数spl_autoload_register和__autoload
    mysql日志配置
    01,易语言网页填表
    mac 的全文搜索
    react native 热更新
    码云的使用教程
    autolayout实现水平三等分
    mac命令行快捷键
    什么是延展性(Malleability,可鍛性)
  • 原文地址:https://www.cnblogs.com/xiebeibei/p/15783497.html
Copyright © 2011-2022 走看看