通過實例來看下 Vue 構造器中需要哪些內容 測試時這段代碼我直接寫在index.html中 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Vue 測試實例 - 菜鳥教程(runoob.com)</title> <script ...
通過實例來看下 Vue 構造器中需要哪些內容
測試時這段代碼我直接寫在index.html中
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Vue 測試實例 - 菜鳥教程(runoob.com)</title> <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script> </head> <body> <div id="vue_det"> <h1>site : {{site}}</h1> <h1>url : {{url}}</h1> <h1>{{details()}}</h1> </div> <script type="text/javascript"> var vm = new Vue({ el: '#vue_det', data: { site: "cyy", url: "www.baidu.com", course: "學習vue" }, methods: { details: function() { return this.site + "開始學習vue~"; } } }) </script> </body> </html>
效果圖
當一個 Vue 實例被創建時,它向 Vue 的響應式系統中加入了其 data 對象中能找到的所有的屬性。當這些屬性的值發生改變時,html 視圖將也會產生相應的變化
上面那一長句其實我沒咋看懂,大概意思就是數據會雙向改變吧!
修改index.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Vue 測試實例 - 菜鳥教程(runoob.com)</title> <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script> </head> <body> <div id="vue_det"> <h1>site : {{site}}</h1> <h1>url : {{url}}</h1> <h1>{{details()}}</h1> </div> <script type="text/javascript"> var data = { site: "cyy", url: "www.baidu.com", course: "學習vue"} var vm = new Vue({ el: '#vue_det', data:data, methods: { details: function() { return this.site + "開始學習vue~"; } } }) // 它們引用相同的對象! document.write(vm.site === data.site) // true document.write("<br>") // 設置屬性也會影響到原始數據 vm.site = "cyy2" document.write(data.site + "<br>") // cyy2 // ……反之亦然 data.course = "學習vue.js" document.write(vm.course) // 學習vue.js </script> </body> </html>
效果圖
除了數據屬性,Vue 實例還提供了一些有用的實例屬性與方法。它們都有首碼 $,以便與用戶定義的屬性區分開來。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Vue 測試實例 - 菜鳥教程(runoob.com)</title> <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script> </head> <body> <div id="vue_det"> <h1>site : {{site}}</h1> <h1>url : {{url}}</h1> <h1>{{details()}}</h1> </div> <script type="text/javascript"> var data = { site: "cyy", url: "www.baidu.com", course: "學習vue"} var vm = new Vue({ el: '#vue_det', data:data, methods: { details: function() { return this.site + "開始學習vue~"; } } }) document.write(vm.$data === data) // true document.write("<br>") document.write(vm.$el === document.getElementById('vue_det')) // true </script> </body> </html>
效果圖