template模板引用
在component的template中书写大量的HTML元素很麻烦。 Vue提供了<template>标签,可以在里边书写HTML,然后通过ID指定到组建内的template属性上;
示例:
由图可知自定义组件的count的值是自增的,是独立的,互不影响。
vue代码:
<template id="my-template"> <div> <h2>{{name}}</h2> <button @click="count++">{{count}}</button> <ul> <li v-for="item in numArray">{{item}}</li> </ul> </div> </template> <script type="text/javascript" src="../js/vue.js" ></script> <script> new Vue({ components:{ "my-component-b":{ template:'#my-template', data(){ return{ name:'欢迎来到perfect*的博客园_01', numArray:[1,2,3,4,5], count:0 } } } } }).$mount('div'); </script>
html:
<body>
<div>
<my-component-b></my-component-b><!--可以把my-component-b看做一个对象-->
<my-component-b></my-component-b><!--可以把my-component-b看做一个对象-->
</div>
</body>
在一个元素上挂载多个组件,根据不同状态进行切换的时候,可以使用动态组件;
动态组件的使用:
需要使用内置组件<component></component>,根据 :is 的值决定显示哪个组件,:is的值是要显示的组件id;
示例:
初始效果:
初始代码:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>动态组件</title> 6 </head> 7 <body> 8 <div> 9 <my-component-a></my-component-a> 10 <my-component-b></my-component-b> 11 <my-component-c></my-component-c> 12 13 </div> 14 </body> 15 16 17 <script type="text/javascript" src="../js/vue.js" ></script> 18 <script> 19 20 new Vue({ 21 22 23 24 25 components:{ 26 "my-component-a":{ 27 template:'<h1>欢迎来到perfect*的博客园</h1>' 28 29 }, 30 31 "my-component-b":{ 32 template:"<a href='https://www.cnblogs.com/jiguiyan/'> perfect*的博客园 </a>" 33 34 }, 35 "my-component-c":{ 36 template:"<p>perfect*</p>" 37 38 }, 39 40 41 } 42 43 44 45 }).$mount('div'); 46 </script> 47 </html>