Vue之自定义事件$emit

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 <div id="emit">
 9     <show>
10         <show_title slot="show_title" :title="title"></show_title>
11         <show_content slot="show_content" v-for="(item,index) in items" :item="item" :index="index" v-on:remove="removeEle(index)"></show_content>
12     </show>
13 </div>
14 <script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script>
15 <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
16 <script type="text/javascript">
17     Vue.component("show",{
18        template: "<div>" +
19                "<slot name='show_title'></slot>"+
20                "<ul>"+
21                "<slot name='show_content'></slot>"+
22                "</ul>"+
23            "</div>"
24     });
25     Vue.component("show_title",{
26         props: ["title"],
27        template: "<h3>{{title}}</h3>"
28     });
29     Vue.component("show_content",{
30         props: ["item","index"],
31        template: "<ul><li>{{index}}---{{item}}&nbsp;&nbsp;&nbsp;<button @click='remove'>删除</button></li></ul>",
32         methods:{
33             remove:function(index){
34                 this.$emit("remove",index);
35             }
36         }
37     });
38 var v=new Vue({
39    el: "#emit",
40     data: {
41        title: "帅气的猪",
42         items: ["帅气的猪猪1号","帅气的猪猪2号","帅气的猪猪3号"]
43     },
44     methods:{
45        removeEle: function(index){
46            console.log("已删除"+this.items[index]+"OK");
47            this.items.splice(index,1);
48        }
49     }
50 });
51 </script>
52 </body>
53 </html>

Vue组件Component用来模板化开发,以提高代码的复用率。使用时无需new出一个新的实例,直接使用Vue.component({})...使用即可。但是面对前端中的数据时,组件想要实现某种操作的时候,就必须要就用“自定义事件—>$emit”来实现。因为组件是无法直接获取到vue实例中的数据,功能的。关系如下图所示:

 

posted @ 2020-03-23 17:35  奔跑的虫呙牛  阅读(398)  评论(0)    收藏  举报