1. 程式人生 > >Vue系列之 => 元件中的data和methods

Vue系列之 => 元件中的data和methods

使用data
 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
<script src="./lib/jquery2.1.4.min.js"></script> 10 <script src="./lib/Vue2.5.17.js"></script> 11 <link href="https://cdn.bootcss.com/animate.css/3.7.0/animate.css" rel="stylesheet"> 12 </head> 13 14 <body> 15 <div id="app"> 16 <mycom1></mycom1> 17
</div> 18 19 <template id="temp1"> 20 <div> 21 <h1>呵呵嘿嘿嘻嘻</h1> 22 <h2>{{ msg }}</h2> 23 </div> 24 </template> 25 <script> 26 // 元件可以有自己的data資料,元件的data和例項的data不一樣 27 //例項中的data可以為一個物件,在元件中的data必須是一個方法且返回一個物件
28 //元件中的資料和例項中使用的方式一樣 29 Vue.component('mycom1',{ 30 template : '#temp1', 31 data : function(){ 32 return { 33 msg : '這是元件自己定義的data資料' 34 } 35 } 36 }) 37 var vm = new Vue({ 38 el: '#app', 39 data: {}, 40 methods: { 41 42 }, 43 }) 44 45 </script> 46 </body> 47 48 </html>

使用methods >> 為什麼元件中的data必須要用function

 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     <script src="./lib/jquery2.1.4.min.js"></script>
10     <script src="./lib/Vue2.5.17.js"></script>
11     <link href="https://cdn.bootcss.com/animate.css/3.7.0/animate.css" rel="stylesheet">
12 </head>
13 
14 <body>
15     <div id="app">
16         <counter></counter>
17         <hr>
18         <counter></counter>
19         <hr>
20         <counter></counter>
21         <hr>
22     </div>
23 
24     <template id="tmp1">
25         <div>
26             <input type="button" value="點我+1" @click="increment">
27             <h3>{{ count }}</h3>
28         </div>
29     </template>
30     <script>
31         // 在外部定義一個物件
32         var dataObj = { count : 0}
33         // 這是一個計數器的元件
34         Vue.component('counter',{
35             template : '#tmp1',
36             data : function(){
37                 // 直接return外部的dataObj,此時會有一個問題,3個計時器共用了這個物件,
38                 //當點選第一個計時器,其他計時器也跟著增加了。
39                 // return dataObj 這種方式是錯誤的
40                 return {count : 0} //使用function來防止
41             },
42             methods: {
43                 increment(){
44                     this.count++
45                 }
46             },
47         })
48 
49         var vm = new Vue({
50             el: '#app',
51             data: {},
52             methods: {
53 
54             },
55         })
56 
57     </script>
58 </body>
59 
60 </html>