vue.js既然是框架,那就不能只是簡單的完成數據模板引擎的任務,它還提供了頁面布局的功能。本文詳細介紹使用vue.js進行頁面布局的強大工具,vue.js組件系統。
Vue.js組件系統
每一個新技術的誕生,都是為了解決特定的問題。組件的出現就是為了解決頁面布局等等一系列問題。vue中的組件分為兩種,全局組件和局部組件。
組件的注冊
全局組件的注冊
通過Vue.component()創建一個全局組件之后,我們可以在一個通過 new Vue 創建的 Vue 根實例中,把這個組件作為自定義元素來使用。
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title> <script src="../statics/vue.min.js"></script></head><body> <div id="app"> <!--第二步,使用--> <global_component></global_component> </div> <script> // 第一步,注冊 Vue.component("global_component", { template: ` <div> <h2>Hello Vue</h2> </div> ` }); new Vue({ el: "#app", }); </script></body></html>組件的參數
因為組件是可復用的 Vue 實例,所以它們與 new Vue 接收相同的選項,例如 data 、 computed 、 watch 、 methods 以及生命周期鉤子等。僅有的例外是像 el 這樣根實例特有的選項。
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title> <script src="../statics/vue.min.js"></script></head><body> <div id="app"> <!--第二步,使用--> <global_component></global_component> </div> <script> // 第一步,注冊 Vue.component("global_component", { data: function () { return { count: 0 } }, template: `<button v-on:click="count++">You clicked me {{ count }} times.</button>` }); new Vue({ el: "#app", }); </script></body></html>組件的復用
每個實例維護自己的一份獨立的數據。
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title> <script src="../statics/vue.min.js"></script></head><body> <div id="app"> <!--第二步,使用--> <global_component></global_component> <global_component></global_component> <global_component></global_component> </div> <script> // 第一步,注冊 Vue.component("global_component", { data: function () { return { count: 0 } }, template: `<button v-on:click="count++">You clicked me {{ count }} times.</button>` }); new Vue({ el: "#app", }); </script></body></html>注意當點擊按鈕時,每個組件都會各自獨立維護它的 count 。因為你每用一次組件,就會有一個它的新 實例 被創建。
新聞熱點
疑難解答
圖片精選