无法加载

Vue简单父子通信

FavoriteLoading收藏

1、父传子

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <title>父传子</title>
  </head>
  <body>
    <div id="app">
      <p>父组件</p>
      <child :myname="name"></child>
    </div>
    <script>
      Vue.component('child', {
        template: `<div>
                接收父组件名字:{{myname}}
                </div>`,
        props: ['myname'],
        //属性验证
        // props: {
        //   myname: String,
        //   myshow: Boolean,
        // },
      })
      new Vue({
        el: '#app',
        data: {
          name: 'qinhao',
        },
      })
    </script>
  </body>
</html>

2、子传父

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <title>子传父</title>
  </head>
  <body>
    <div id="app">
      <p>父组件状态</p>
      <child @myevent="handleEvents"></child>
    </div>
    <script>
      Vue.component('child', {
        template: `<div>
                <button @click="payMoney()">click</button>
                </div>`,
        data() {
          return {
            message: '子组件状态',
          }
        },
        methods: {
          payMoney() {
            this.$emit('myevent', this.message)
          },
        },
      })
      new Vue({
        el: '#app',
        methods: {
          handleEvents(ev) {
            alert(ev)
          },
        },
      })
    </script>
  </body>
</html>

留下评论

微信:15182814906

QQ:1548902957

邮箱:1548902957@qq.com