1 <!DOCTYPE html>
2 <html>
3
4 <head>
5 <meta charset="UTF-8">
6 <title>拆分組件</title>
7 <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
8 </head>
9 <style>
10 button {
11 background: blue;
12 height: 32px;
13 width: 120px;
14 border: 1px solid blue;
15 color: #FFFFFF;
16 margin-top: 20px;
17 font-size: 14px;
18 }
19 </style>
20
21 <body>
22 <div id="root">
23 <input type="text" name="" id="" v-model="msg" />
24 <button @click="add">添加</button>
25 <!--list顯示-->
26 <ul>
27 <li-cell v-for="(item ,index) of list" :key="index" :content="item"></li-cell>
28 </ul>
29
30 </div>
31 <script type="text/javascript">
32 // 全局組件
33 Vue.component('li-cell', { 34 props: ['content'], // 添加content屬性后
35 template: "<li>{{content}}</li>" // 添加content屬性后
36 }); 37 new Vue({ 38 el: "#root", 39 data: { 40 msg: "", 41 list: [], 42 }, 43 methods: { 44 add: function() { 45 this.list.push(this.msg); 46 this.msg = ""; 47 } 48 } 49 }); 50 </script>
51 </body>
52
53 </html>
二、父組件與子組件之前的交互
示例:刪除功能
1 <!DOCTYPE html>
2 <html>
3
4 <head>
5 <meta charset="UTF-8">
6 <title>通過簡單的刪除功能來理解父組件與子組件之間的數據傳遞</title>
7 <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
8 </head>
9 <style type="text/css">
10 button {
11 font-size: 14px;
12 background: skyblue;
13 border: 1px solid skyblue;
14 width: 100px;
15 height: 30px;
16 border-radius: 4px;
17 }
18 </style>
19
20 <body>
21 <!--實現效果點擊li刪除-->
22 <div id="root">
23 <input type="text" v-model="msg" />
24 <button @click="add">添加</button>
25 <ul>
26 <itme-cell v-for="(item,index) of list" :key="index" :index="index" :content="item" @delete="handle"></itme-cell>
27 </ul>
28 </div>
29 <script>
30 // 一般的刪除思路:點擊li,找到當前li的父級ul,進行刪除;
31
32 // 該組件是子組件
33 Vue.component('itme-cell',{ 34 props:['content','index'] ,// 接受父組件傳遞過來的索引index
35 template:'<li @click="deleteLi">{{content}}</li>',// 我們先給li綁定刪除事件
36 methods:{// 當li被點擊時,會觸發deleteLi
37 deleteLi:function(){ 38 // alert(this.index);
39 this.$emit('delete',this.index);// 此處表示向外觸發刪除事件,即父組件中的delete事件,並同時把索引傳遞給父組件。從而讓父組件去執行handle 的方法;
40 } 41 } 42 }); 43
44 // 最外層的vue實例是父組件
45 new Vue({ 46 el: '#root', 47 data: { 48 msg: "", 49 list: [] 50 }, 51 methods:{ 52 add:function(){// 當添加按鈕別點擊時會觸發該add方法
53 this.list.push(this.msg); // 因為input值與實例中data的msg變量進行了雙向綁定,所以此處的意思就是:只要點擊添加按鈕,就會獲取input中的值,並把這個值添加到list數組中。然后現在是list數據已經存在了,就在模板中調用v-for對數據進行循環加載即可
54 this.msg="";// 每次添加完成都會清空下input中的值
55 }, 56 handle:function(){ 57 // 把數據移除注意此處一定要是this.index,否則會報錯 ..index not defined..
58 this.list.splice(this.index,1);// splice(索引,要移除的個數);
59 //我自己寫的時候其實是有疑問的,一般的開發我們刪除數據之后還要把當前的dom也在頁面中移除掉。但是為什么此處不用呢?我現在只知道這個方法是vue更改后的,如果調用刪除數組元素的方法vue就會自動更新視圖,這塊我還是不清楚,有知道望解惑下!
60 } 61 } 62 }); 63 </script>
64 </body>
65
66 </html>