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 。因为你每用一次组件,就会有一个它的新 实例 被创建。
新闻热点
疑难解答
图片精选