参考链接:https://www.cnblogs.com/goloving/p/8630603.html
组件基础
- 组件是可复用的 Vue 实例。
- 组件可以扩展HTML元素,封装可重用的HTML代码,我们可以将组件看作自定义的HTML元素。
- 因为组件是可复用的 Vue 实例,所以它们与 new Vue 接收相同的选项,例如 data、computed、watch、methods 以及生命周期钩子等。仅有的例外是像 el 这样根实例特有的选项。
- 一个组件的 data 选项必须是一个函数
- 每个组件必须只有一个根元素
- 为了能在模板中使用,组件必须先注册以便 Vue 能够识别。
有两种组件的注册类型:全局注册和局部注册。
组件的创建和注册基本步骤
Vue.js的组件的使用有3个步骤:创建组件构造器、注册组件和使用组件。
-
全局注册
<!DOCTYPE html> <html> <head> <title></title> <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script> </head> <body> <div id="app"> <!-- 3. #app是Vue实例挂载的元素,应该在挂载元素范围内使用组件--> <my-component></my-component> </div> <script> // 1.创建一个组件构造器 var myComponent = Vue.extend({ template: '<h1>This is my first component!</h1>' }) // 2.注册组件,并指定组件的标签,组件的HTML标签为<my-component> Vue.component('my-component', myComponent) new Vue({ el: '#app' }); </script> </body> </html>
-
局部注册
// 1.创建一个组件构造器 var myComponent = Vue.extend({ template: '<div>This is my first component!</div>' }) new Vue({ el: '#app', components: { // 2. 将myComponent组件注册到Vue实例下 'my-component' : myComponent } });
该局部组件只能在app下才能起作用
父组件和子组件
在组件中定义并使用其他组件,这就构成了父子组件的关系。
子组件只能在父组件的template中使用。
注意下面两种子组件的使用方式是错误的:
1、以子标签的形式在父组件中使用
2、在父组件标签外使用子组件
组件注册语法糖
-
使用Vue.component()直接创建和全局注册组件:
// 全局注册,my-component是标签名称,后面跟模板template Vue.component('my-component',{ template: '<div>This is the first component!</div>' })
相当于把Vue.extend()直接放入第二个参数
-
在选项对象的components属性中实现局部注册:
var vm = new Vue({ el: '#app', components: { // 局部注册,my-component2是标签名称 'my-component2': { template: '<div>This is the second component!</div>' }, // 局部注册,my-component3是标签名称 'my-component3': { template: '<div>This is the third component!</div>' } } })
使用script或template标签
父子组件通讯
组件实例的作用域是孤立的。
父传子
这意味着不能并且不应该在子组件的模板内直接引用父组件的数据。可以使用 props 把数据传给子组件
prop默认是单向绑定:当父组件的属性变化时,将传导给子组件,但是反过来不会。这是为了防止子组件无意修改了父组件的状态。
如果需要,可以使用.sync
显式地指定双向绑定,这使得子组件的数据修改会回传给父组件。
<my-component v-bind:my-name.sync="name" v-bind:my-age.sync="age"></my-component>