zoukankan      html  css  js  c++  java
  • 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) 的结构即可

     效果图

    随笔为本人学习笔记以及个人看法,若有错误,欢迎指正
  • 相关阅读:
    设计模式
    设计模式
    设计模式
    JS | Reduce
    JS | 数组的深拷贝与浅拷贝
    JS | 数组操作
    Lodash | 指定路径对Object操作
    Git | 场景总结
    ES6 Class
    SpringBoot | Jpa @Id @GeneratedValue
  • 原文地址:https://www.cnblogs.com/yjc-vue-react-java/p/13876714.html
Copyright © 2011-2022 走看看