zoukankan      html  css  js  c++  java
  • Vue 父子组件传递数据

    Vue父组件给子组件传值:

    父组件:

    <template>
      <div class="father">
        {{ message }}
        <Son v-bind:message="message"></Son>
      </div>
    </template>
    
    <script>
    //导入Son组件
    import Son from "./Son";
    export default {
      name: "father",
      data() {
        return {
          message: "hello, father",
        };
      },
      components: {
        Son,
      },
      methods: {},
    };
    </script>
    

      

    子组件:

    <template>
      <div class="son">子元素: {{ message }}</div>
    </template>
    
    <script>
    export default {
      name: "son",
      props: {
        message: {
          type: String,
          default: "",
        },
      },
      data() {
        return {};
      },
    };
    </script>
    

    父组件传子组件,props是关键;

    Vue子组件给父组件传值:

     父组件:

    <template>
      <div class="father">
        <p>{{ message }}</p>
        <!-- @receiveData="receiveData"一定要写在子标签上 -->
        <Son v-bind:message="message" @receiveData="receiveData"></Son>
      </div>
    </template>
    
    <script>
    //导入Son组件
    import Son from "./Son";
    export default {
      name: "father",
      data() {
        return {
          message: "hello, father",
        };
      },
      components: {
        Son,
      },
      methods: {
        /**
         * 接收子组件数据
         */
        receiveData(message) {
          this.message = message;
        },
      },
    };
    </script>
    

      

    子组件:

    <template>
      <div class="son">
        <p>子元素: {{ message }}</p>
        <button @click="transferData">click</button>
      </div>
    </template>
    
    <script>
    export default {
      name: "son",
      props: {
        message: {
          type: String,
          default: "",
        },
      },
      data() {
        return {};
      },
      methods: {
        transferData() {
          //调用父组件接收子组件数据方法,传递数据
          this.$emit("receiveData", "son数据:hello, father!");
        },
      },
    };
    </script>
    

    子组件传父组件,emit方法是关键;

  • 相关阅读:
    浏览器渲染机制
    isEmpty 和 isBlank 的用法区别
    Mybatis-plus
    Java8的JVM内存结构
    【面试题】关于线程交替的面试题
    java中的final的作用
    线程池
    六种实现单例模式的方法
    SQL优化常用方法
    HTML学习笔记
  • 原文地址:https://www.cnblogs.com/mxh-java/p/13462938.html
Copyright © 2011-2022 走看看