Vue2 父子组件互相传值

2019-09-25  本文已影响0人  Leo_23
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <script src="https://cdn.bootcss.com/vue/2.6.10/vue.js"></script>
  </head>
  <body>
    <div id="app">
      <child v-bind:msg="fatherdata" @func="getSonMsg"></child>
    </div>
    <template id="child">
      <div>
        <h1>child -- {{ msg }}</h1>
        <input
          type="button"
          value="send smg to father"
          @click="sendMsgToFather"
        />
      </div>
    </template>
    <script>
      var child = {
        template: "#child",
        props: ["msg"],
        data() {
          return {
            childmsg: "child msg"
          };
        },
        methods: {
          sendMsgToFather() {
            this.$emit("func", this.childmsg);
          }
        }
      };
      var vm = new Vue({
        el: "#app",
        data: {
          fatherdata: "123"
        },
        methods: {
          getSonMsg(data) {
            console.log(data);
          }
        },
        components: {
          child
        }
      });
    </script>
  </body>
</html>
上一篇 下一篇

猜你喜欢

热点阅读