【Vue】组件传参-字传父

时间:2024-01-21 17:46:36

关键字
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>