其他分享
首页 > 其他分享> > vue子父组件通信

vue子父组件通信

作者:互联网

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
  </head>

  <body>
    <div id="app">
      <comp @cbookclick='onbookclick'> </comp>
    </div>

    <template id="comp">
      <div id="">
        <p>{{message}}</p>
        <button type="button" v-for="book in books" @click="onclick(book)">{{book.name}}</button>
    </template>

    <script>
      // 子组件
      const comp = Vue.extend({
        template: '#comp',
        data() {
          return {
            message: 'Hello Vue.js!',
            books: [{
                name: 'HTML/HTML5基础',
                price: 15.5,
              },
              {
                name: '高健壮性CSS',
                price: 16.5,
              },
              {
                name: '深入学习JS',
                price: 17.5,
              },
            ]
          }
        },
        methods: {
          onclick(book) {
            console.log('onclick ' + book.name);
            // 发送信号给父组件
            this.$emit('cbookclick');
          }
        }
      })

      // root
      const app = new Vue({
        el: '#app',
        components: {
          comp,
        },
        methods: {
          onbookclick() {
            console.log('onbookclick');
          }
        }
      })
    </script>
  </body>
</html>

标签:vue,子父,name,comp,price,Vue,组件,book
来源: https://www.cnblogs.com/zhangxuechao/p/14976101.html