Vue,组件-why componets data must be a function
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 7 <title>Document</title> 8 <script src="../js/vue.js"></script> 9 </head> 10 <body> 11 <div id="app"> 12 <counter></counter> 13 <hr> 14 <counter></counter> 15 <hr> 16 <counter></counter> 17 </div> 18 19 <template id="tmpl"> 20 <div> 21 <!-- increment 自增 --> 22 <input type="button" value="+1" @click="increment" > 23 <h3> {{ count }} </h3> 24 </div> 25 </template> 26 27 </body> 28 </html> 29 <script> 30 31 // 在外部定义一个对象, 放到计数器组件中 32 // 这样是可以的, 但仅限单个组件,如果是多个组件的话组件会一起变 33 var dataObj = { count: 0} 34 35 // 这是一个计数器组件, 身上有个按钮, 每当点击按钮, 让 data 中的 count 值 +1 36 Vue.component('counter', { 37 template:'#tmpl', 38 data: function(){ 39 // 最好不要在外部定义 40 // return dataObj; 41 42 // 三个组件不会一起增加, 会单独增加, 这就是为什么要在内部定义对象 43 return { count: 0 } 44 }, 45 methods:{ 46 increment(){ 47 // this.count +=1 48 this.count++ 49 } 50 } 51 }) 52 53 var vm = new Vue({ 54 el: '#app', 55 data: { }, 56 methods: { } 57 }) 58 59 60 </script>
效果图
