vue3的新寫法和特性整理——四、子父組件之間傳值


只貼出了vue3中新的子父組件傳值,V3兼容老的寫法就不再贅述
1、父組件

<template>
  <div class="home">
    <h1>父組件</h1>
    <img alt="Vue logo" src="../assets/logo.png" />
    <HelloWorld :msg="msg" />
  </div>
</template>

<script>
import { reactive, toRefs } from 'vue';
import HelloWorld from "@/components/HelloWorld";
export default {
  setup() {
    const state = reactive({
      msg: '父組件傳值'
    });

    return {
      ...toRefs(state)
    };
  },
  name: 'Home',
  components: {HelloWorld},
};
</script>

<style scoped>
.home {
  color: red;
  border: 1px solid red;
}
</style>

  2、子組件

<template>
  <div class="hello">
    <h1>子組件</h1>
    <h1>{{ msg }}</h1>
  </div>
</template>

<script>
import { toRefs } from 'vue';
export default {
  setup(props) {
    console.log(props);
    return {
      ...toRefs(props)
    };
  },
  name: 'HelloWorld',
  props: {
    msg: String
  }
};
</script>

<style scoped>
.hello {
  margin: 20px;
  color: green;
  border: 1px solid green;
}
</style>

  
setup函數的第一個參數能取到父組件的傳值,然后在函數中返回  toRefs(props) 的結構即可

 效果圖

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM