• Vue3中常见传值方式


    Vue3中常见传值方式

    Props 方式

    <template>
      <!-- 父组件-->
      <Bar :msg="'prop传值'"/>
    </template>
    
    <script setup>
      import Bar from './bar.vue'
    </script>
    
    ------------------------------------
    <template>
      <!-- 子组件 -->
      <h1>{{ msg }}</h1>
    
      <button type="button" @click="count++">
        fei 数量 {{ count }}
      </button>
    
    </template>
    
    <script setup>
      import { ref } from 'vue'
      defineProps({msg: String})
      const count = ref(0)
    </script>
    View Code

    Emits 方式

    <template>
      <!-- 父组件-->
      <Bar @add="handleFei"/>
    </template>
    
    <script setup>
      import Bar from './bar.vue'
      const handleFei = (value) => {
        console.log("接受参数:", value);
      }
    </script>
    
    ------------------------------------
    <template>
      <!-- 子组件 -->
      <button @click="feiClick">点击我触发emits</button>
    </template>
    
    <script setup>
      import { defineEmits  } from 'vue'
      const emits = defineEmits(['add'])
      const feiClick = () => {
        emits("add","我是参数,传给父组件")
      }
    </script>
    View Code

    DefineExpose 父调子

    <template>
      <!-- 父组件-->
      <button @click="feiClick" >点击我触发emits</button>
      <Bar ref="feiRef"/>
    </template>
    
    <script setup>
      import Bar from './bar.vue'
      import {ref} from "vue";
      const feiRef = ref(null);
      const feiClick = () => {
        // 调用子组件
        feiRef.value.childrenFei();
      }
    </script>
    
    ------------------------------------
    <template>
      <!-- 子组件 -->
    </template>
    <script setup>
     const childrenFei = () => {
       console.log("接受父组件方法");
     }
     // 暴露出去方法,让父组件调用
     defineExpose({
       childrenFei
     })
    </script>
    View Code

    Provide/Inject 隔代传递

    <template>
      <!-- 父组件-->
      <Bar />
    </template>
    
    <script setup>
      import Bar from './bar.vue'
      import {provide} from "vue";
      provide('list',"可以隔代传给子组件")
    </script>
    
    ------------------------------------
    <template>
      <!-- 子组件 -->Provide/Inject
      <p>{{fei}}</p>
    </template>
    <script setup>
      import {inject} from "vue";
      const fei = inject("list")
    </script>
    View Code

     

     

     

  • 相关阅读:
    linux启动init流程(转)
    .bash_profile .bashrc profile 文件的作用的执行顺序(转)
    Linux常用命令
    面试中常见的问题
    systemd启动过程(转)
    .bashrc文件是干什么的(转)
    关于 profile文件(转)
    从MVC框架看MVC架构的设计(转)
    Java高级软件工程师面试考纲(转)
    关于Python中的lambda
  • 原文地址:https://www.cnblogs.com/dafei4/p/15934657.html
Copyright © 2020-2023  润新知