Vue3—父子组件传值(子组件使用 emit 传值到父组件)

Vue3—父子组件传值(子组件使用 emit 传值到父组件)Vue3中,子组件通过setup函数中的第一个参数值props拿到定义的组件参数进行使用。如果要向父组件传参,需要使用setup函数中的第二个参数值context(组件上下文)中的emit。例1:Tab菜单子组件创建子组件Tabs.vue<template><divclass=”Tabs”><divv-for=”(menu,index)inlistMenu”:key=”index”…

大家好,又见面了,我是你们的朋友全栈君。

    Vue3中,子组件通过setup函数中的第一个参数值 props 拿到定义的组件参数进行使用。如果要向父组件传参,需要使用setup函数中的第二个参数值 context(组件上下文)中的emit。

官网APIicon-default.png?t=L892https://v3.cn.vuejs.org/guide/migration/emits-option.html

  例1:Tab菜单子组件

  • 创建子组件Tabs.vue
<template>
    <div class="Tabs">
        <div v-for="(menu, index) in listMenu" :key="index" 
            @click="menuClick(menu.name)"
            :class="{ 'mactive' : menu.isActive === true ? true : false }">
            {
  
  { menu.name }}
        </div>
    </div>
</template>
<script>
import { defineComponent, ref } from 'vue'
export default defineComponent({
    name: 'Tabs',
    props: {
        listMenu: { // 菜单数据
            type: Array,
            required: true,
            default(){
                return []
            }
        }
    },
    setup(props, context){
        const listMenu = props.listMenu
        function menuClick (menuName) {
            // 通过自定义事件回传值
            context.emit('menuClick', { menuName })
        }
        return {
            listMenu,
            menuClick
        }
    }
})
</script>
<style lang='scss'>
    .Tabs{
        padding: 0;
        margin: 0;
        display: flex;
        align-items: center;
        justify-content: space-around;
        height: 50px;
        background-color: #0087AC;
        color: black;
    }
    .mactive{
        color: white;
        font-weight: bold;
    }
</style>
  • 父组件
<template>
  <!--使用子组件,传值并监听子组件自定义事件拿值-->
  <Tabs :listMenu="listMenu" @menuClick="menuClick" />
</template>
<script>
import { defineComponent, ref } from "vue";
import Tabs from '../components/Tabs'

export default defineComponent({
  name: "Index",
  components: {
    Tabs
  },
  setup() {
    const listMenu = ref([
      {
        name : '总部',
        isActive : true
      },
      {
        name : '地球',
        isActive : false
      },
      {
        name : '火星',
        isActive : false
      }     
    ])
    function menuClick (param) {
      listMenu.value.forEach(item => {
        item.isActive = item.name === param.menuName ? true : false
      })
    }
    return {
      listMenu,
      menuClick
    }
  }
});
</script>

    

Vue3---父子组件传值(子组件使用 emit 传值到父组件)

  例2:搜索子组件

  • 创建子组件Search.vue
<template>
    <div class="searchInp">
        <div class="inp">
            <input type="text" :placeholder="placeholder" v-model="search.content" />
            <span @click="handlerSearch">搜索</span>
        </div>
    </div>
</template>
<script>
import { defineComponent, ref } from 'vue'

export default defineComponent({
    name: 'Search',
    props: {
        tip: {
            type: String,
            reuquired: false,
            default: ''
        }
    },
    setup(props, { emit }) {
        const placeholder = props.tip
        const search = ref({
            content: ''
        })
        function handlerSearch () {
            emit('searchClick', search.value)
        }
        return {
            placeholder,
            search,
            handlerSearch
        }
    }
})
</script>
<style lang="scss">
    .searchInp{
        height: 40px;
        line-height: 40px;
        width: 100%;
        background-color: #0087AC;
        border-radius: 20px;
        color: white;
    }
    .inp input{
        width: 80%;
        height: 30px;
        line-height: 30px;
        background-color: transparent;
        border: none;
        outline: none;
        color: white;
    }
    .inp input::-webkit-input-placeholder{
        color: white;
    }
    .inp span{
        width: 20%;
    }
</style>
  • 父组件
<template>
  <!--使用子组件,传值并监听子组件自定义事件拿值-->
  <Search tip="请输入搜索内容" @searchClick="searchClick" />
  <h3>子组件传值内容:{
  
  { searchCon }}</h3>
</template>
<script>
import { defineComponent, ref } from "vue";
import Search from '../components/Search'

export default defineComponent({
  name: "Index",
  components: {
    Search
  },
  setup() {
    const searchCon = ref('')
    function searchClick (searCon) {
      searchCon.value = searCon.content
    }
   
    return {
      searchClick,
      searchCon
    }
  }
});
</script>

Vue3---父子组件传值(子组件使用 emit 传值到父组件)

   例3:也可以在模板中直接使用 $emit 来传自定义事件到父组件

  •  子组件
<template>
  <div>
    <h1 @click="changeName();$emit('aboutEvent', name)">This is an about page</h1>
  </div>
</template>
<script>
import { defineComponent, ref } from 'vue'
export default defineComponent({
  name: 'AboutComponent',
  setup(){
    const name = ref('About')
    function changeName () {
      name.value = 'AboutComponent'
    }
    return {
      changeName,
      name
    }
  }
})
</script>
  •  父组件
<template>
  <div class="about">
    <AboutComponent @aboutEvent="handleEvent" />
  </div>
</template>
<script>
import { defineComponent, defineAsyncComponent } from 'vue'
export default defineComponent({
  name: 'About',
  components: {
    AboutComponent: defineAsyncComponent(() => import('@/components/AboutComponent'))
  },
  setup () {
    function handleEvent (param) {
      console.log(param)
    }
    return {
      handleEvent
    }
  }
})
</script>

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/145289.html原文链接:https://javaforall.net

赞 (0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • websocket设置header(HttpCanary)

    OkHttpClient的性能要优于HttpClient,因此本例来教大家如何配置使用它.在要使用的地方直接@Autowired即可:测试:

    2022年4月16日
  • Mybatis与Spring集成:SqlSessionTemplate[通俗易懂]

    Mybatis与Spring集成:SqlSessionTemplate[通俗易懂]Mybatis与Spring集成:SqlSessionTemplateSqlSessionTemplate构造方法publicSqlSessionTemplate(SqlSessionFactorysqlSessionFactory,ExecutorTypeexecutorType,PersistenceExceptionTranslatorexceptionTra…

    2022年5月31日
  • pycharm中安装opencv2_starter安装报错

    pycharm中安装opencv2_starter安装报错图像处理新人,想练习一下opencv库在PyCharm终端pipinstallopencv-python显示安装失败!!!查看了一下竟然是因为BOSEInterpreter是Anaconda去官网上下载了个python解释器就好了!!!给自己提个醒吧!

    2022年8月25日
  • OriginPro绘图过程中遇到的问题及解决办法

    OriginPro绘图过程中遇到的问题及解决办法y轴标题如何只显示单位不显示长名称?选中坐标轴标题,右击,选择属性,将文本内容由%(?Y)改为%(?Y,@lu),即可。此为软件内部代码,可以正常使用。

    2022年5月29日
  • 智能家居产业链分析

    智能家居产业链分析“一盘散沙,各自为营”是目前国内智能家居产业生态的真实写照。从地域上来看,北京、华南地区比较活跃。北京高校、科研院所云集,具备雄厚的科技力量优势,华南地区的中小企业多,也较为活跃。“这也和十几年前一样,智能家居这块目前还是小企业更为活跃,大企业在等待时机。”广东华南家电研究院院长孙颖楷向记者表示。“从传统的家具行业角度划分,上游是元器件厂商,如传感器、芯片等;中游是控制器和控制软件

    2022年6月22日
  • linux怎么修改命令行怎么退出,linux vi保存退出命令(如何退出vi)[通俗易懂]

    linux怎么修改命令行怎么退出,linux vi保存退出命令(如何退出vi)[通俗易懂]有很多方法:退出Vi当编辑完文件,准备退出Vi返回到shell时,可以使用以下几种方法之一。在命令模式中,连按两次大写字母Z,若当前编辑的文件曾被修改过,则Vi保存该文件后退出,返回到shell;若当前编辑的文件没被修改过,则Vi直接退出,返回到shell。在末行模式下,输入命令:wVi保存当前编辑文件,但并不退出,而是继续等待用户输入命令。在使用w命令时,可以再给编辑文件起一个新的文件名。[例…

    2022年9月27日

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号