【Vue】组件传参

发布时间:2024年01月20日

父传子

关键字
:参数
defineProps

父组件代码

<script setup>
  import {ref} from 'vue'
  import Header from"./components/Header.vue"
  import Navigator from"./components/Navigator.vue"
  import Content from"./components/Content.vue"  

  let message =ref('parent data!')
  let title=ref(42)
  function changeMessage(){
    message.value='修改数据'
    title.value++
  }
</script>

<template>
  <div>
    {{ message }}
    <button @click="changeMessage"></button>
    <Header class="header"></Header>
    <Navigator class="navigator"></Navigator>
    <Content class="content" :message="message" :title="title"></Content> 
    
  </div>
</template> 

<style scoped>
  .header{
    height: 80px;
    border: 1px solid red;
  }
  .navigator{
    width: 15%;
    height: 800px;
    display: inline-block;
    border: 1px blue solid;
    float: left;
  }
  .content{
      width: 83%;
      height: 800px;
      display: inline-block;
      border: 1px goldenrod solid;
      float: right;
    }
</style>

子组件代码

<script setup>
  import {ref,isRef,defineProps} from 'vue'
  defineProps({
    message:String,
    title:Number
  })
</script>

<template>
  <div>
    Content:展示主要内容<br>
    {{ message }}<br>
    {{ title }}
  </div>
</template>

<style scoped>
</style>

字传父

关键字
const x=(参数)=>{赋值}
let emits=defineEmits([‘n’])
在别处,emits(‘n’,一个值),就可以给父组件传参了

父组件

<script setup>
  import {ref} from 'vue'
  import Header from"./components/Header.vue"
  import Navigator from"./components/Navigator.vue"
  import Content from"./components/Content.vue"  
  
  let n=ref(0)
  const rn=(data)=>{
    n.value=data
  }
</script>

<template>
  <div>
    {{ n }}
    <Header class="header" @n="rn"></Header>
    <Navigator class="navigator"></Navigator>
    <Content class="content" ></Content> 
    
  </div>
</template> 

<style scoped>
  .header{
    height: 80px;
    border: 1px solid red;
  }
  .navigator{
    width: 15%;
    height: 800px;
    display: inline-block;
    border: 1px blue solid;
    float: left;
  }
  .content{
      width: 83%;
      height: 800px;
      display: inline-block;
      border: 1px goldenrod solid;
      float: right;
    }
</style>

子组件

<script setup>
  import {ref,defineEmits} from 'vue'
  let emites=defineEmits(['n'])

  let data=ref(1);
  function sendMsgToParent(){
    data.value++
    emites('n',data.value)
  }
</script>

<template>
  <div>
    <button @click="sendMsgToParent">+</button>
  </div>
</template>

<style scoped>
</style>
文章来源:https://blog.csdn.net/m0_69886881/article/details/135716938
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。