zoukankan      html  css  js  c++  java
  • vue 组件通信 子>父 与 父>子 双向传递数据

     1 <!DOCTYPE html>
     2 <html lang="en">
     3 
     4 <head>
     5     <meta charset="UTF-8">
     6     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     7     <meta http-equiv="X-UA-Compatible" content="ie=edge">
     8     <title>Document</title>
     9 </head>
    10 
    11 <body>
    12     <!-- 父组件模板 -->
    13     <div id="app">
    14  <!--子向父 将子组件事件与父组件事件进行绑定 |父向子 将父组件中categories与子组件中subcategories进行绑定-->
    15         <cpn @itemclick="cpnclick" :subcategories="categories" :submessage="message"></cpn>
    16     </div>                                  
    17 
    18 
    19     <!-- 子组件模板 -->
    20     <template id="cpn">
    21         <div>           
    22             <!-- 遍历子组件中subcategories接收到的数据 -->
    23             <button v-for="item in subcategories" @click="btnclick(item)">{{item.name}}</button>
    24             <!-- <input v-for="item in subcategories" @click="btnclick(item)" :value="item.name"></input> -->
    25             <h2>{{submessage}}</h2>
    26         </div>
    27 
    28     </template>
    29     <script type="text/javascript" src="../js/vue.js"></script>
    30     <script>
    31         const cpn = {
    32             template: '#cpn',
    33             props:{
    34                 //接收父组件的数据
    35                 subcategories:{
    36                     type:Array
    37                 },
    38                 submessage:{
    39                     type:String
    40                 }
    41             },
    42             methods: {
    43                 btnclick(item) {
    44                     this.$emit('itemclick', item)
    45                 }//子组件可以使用 $emit 触发父组件的自定义事件
    46             }
    47         }
    48         const vm = new Vue({
    49             el: '#app',
    50             data: {
    51                 message: 'hello',
    52                 categories: [
    53                         { id: '111', name: '热门推荐' },
    54                         { id: '222', name: '手机数码' },
    55                         { id: '333', name: '家用电器' },
    56                         { id: '444', name: '电脑办公' },
    57 
    58                     ]
    59             },
    60             components: {
    61                 cpn
    62             },
    63             computed: {
    64 
    65             },
    66             methods: {
    67                 cpnclick(item) {
    68                     console.log(item);
    69                 }  //父组件中的自定义事件
    70             }
    71         });
    72     </script>
    73 </body>
    74 
    75 </html>
  • 相关阅读:
    [日常训练]FJ省夏令营day1
    [vijos1002][NOIP2005]过河
    [poj2446]Chessboard
    [bzoj1854][SCOI2010]游戏
    [模板]匈牙利算法
    [bzoj3670][2014湖北省队互测week2]似乎在梦中见过的样子
    笔记3-27
    笔记3-26
    笔记3-25
    Codeforces891C. Envy
  • 原文地址:https://www.cnblogs.com/lixia0604/p/15652180.html
Copyright © 2011-2022 走看看