美文网首页
组件通信-子组件给父组件传递

组件通信-子组件给父组件传递

作者: 木羽木羽女口生 | 来源:发表于2020-12-27 00:26 被阅读0次
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <div id="app">
        <cpn @item-click="cpnClick"></cpn>
    </div>
    <script src="../js/vue.js"></script>
    <template id="cpn">
        <div>
            <button v-for="item in categories" @click="btnClick(item)">{{ item.name }}</button>
        </div>
    </template>
    <script>
    
      //1.子组件
      const cpn = {
        template: '#cpn',
        data(){
          return {
            categories: [
              {id: 'aaaa',name:'热门推荐'},
              {id: 'bbbb',name:'手机数码'},
              {id: 'cccc',name:'家用电器'},
              {id: 'dddd',name:'电脑办公'},
              {id: 'ffff',name:'其它'}
            ]
          }
        },
        methods: {
          btnClick(item){
            this.$emit('item-click',item)
          }
        }
      }
    
      //2.父组件
      const app = new Vue({
        el: '#app',
        data: {
    
        },
        components: {
          cpn
        },
        methods: {
            cpnClick(item){
              console.log(item.name);
            }
    
        }
      })
    </script>
    </body>
    </html>
    
    

    相关文章

      网友评论

          本文标题:组件通信-子组件给父组件传递

          本文链接:https://www.haomeiwen.com/subject/bsbnnktx.html