组件 Component
组件(Component)是 Vue.js 最强大的功能之一。
组件可以扩展 HTML 元素,封装可重用的代码(即模板template)。
全局组件
全局组件意味着所有实例都可以使用这个组件
1 2 3 4 5 6
| <div id="app"> <my-com></my-com> </div> <div id="app1"> <my-com></my-com> </div>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| Vue.component('my-com',{ template:'<h1>{{msg}}</h1>', data:function () { return{ msg:'hello' } } }); new Vue({ el:'#app' }); new Vue({ el:'#app1' });
|
※实例基本没什么限制,只要不是挂载到本身就可以☞ el:'my-com'
是行不通的
※此外组件的data
要在注册时候写,并且data
里只能是个return
出来的返回值
局部组件
我们也可以在实例选项中注册局部组件,这样组件只能在这个实例中使用
1 2 3 4 5
| <div id="app"> <com-one></com-one> <com-two></com-two> </div>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| var data={ msg1:'hello', msg2:'vue' } var temOne={ template:'<h1>{{msg1}}</h1>', data:function () { return data; } }; var temTwo={ template:'<h1>{{msg2}}</h1>', data:function () { return data; } }; new Vue({ el:'#app', components:{ 'com-one':temOne, 'com-two':temTwo } });
|
模板
当template
里面内容很多,已经不仅仅是一行代码的时候,我们可以在html
部分添加<template>
标签并且引用它
1 2 3 4 5 6 7 8 9 10 11 12 13
| <body> <div id="app"> <poem></poem> </div> <template id="my-temp"> <dl> <dt>今日は 风が 骚がしいな</dt> <dd>天気がいいから</dd> <dd>散歩しましょう</dd> </dl> </template> </body>
|
1 2 3 4 5 6
| Vue.component('poem',{ template:'#my-temp' }) var vm=new Vue({ el:"#app" })
|
注意: 因为Vue
只有在浏览器解析和标准化HTML
后才能获取模版内容。尤其像这些元素<ul> 、<ol>、<table>、<select>
限制了能被它包裹的元素,<option>
只能出现在其它元素内部。
1 2 3 4 5 6 7 8
| <table> <my-row>...</my-row> </table> <table> <tr is="my-row"></tr> </table>
|
Tips: 长命名在html
里使用kebab-case
短横线写法,js里采取camelCase
驼峰命名法
动态组件
多个组件可以使用同一个挂载点,然后动态地在它们之间切换。使用保留的 元素,动态地绑定到它的 is 特性
1 2 3
| <div id="app"> <component v-bind:is="currentView"></component> </div>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| var comA = { template: '<h1>a</h1>' }; var comB = { template: '<h2>b</h2>' } var vm = new Vue({ el: "#app", components: { "com-a": comA, "com-b": comB }, data: { currentView: "com-b" } })
|
keep-alive
如果把切换出去的组件保留在内存中,可以保留它的状态或避免重新渲染。为此可以添加一个 keep-alive 指令参数:
1 2 3 4 5
| <keep-alive> <component :is="currentView"> </component> </keep-alive>
|
子组件索引
尽管有 props 和 events ,但是有时仍然需要在 JavaScript 中直接访问子组件。为此可以使用 ref 为子组件指定一个索引 ID
1 2 3
| <div id="parent"> <child-com ref="profile" name="mary"></child-com> </div>
|
1 2 3 4 5 6 7 8 9 10
| Vue.component('child-com', { template: '<span>{{name}}</span>', props: ["name"] }) var parent = new Vue({ el: "#parent" }) var child = parent.$refs.profile; console.log(child.name);
|