Vue 组件&组件之间的通信 之 template模板引用与动态组件的使用 |
您所在的位置:网站首页 › vue组件模板中包含插值吗 › Vue 组件&组件之间的通信 之 template模板引用与动态组件的使用 |
template模板引用
在component的template中书写大量的HTML元素很麻烦。 Vue提供了标签,可以在里边书写HTML,然后通过ID指定到组建内的template属性上;
示例: 由图可知自定义组件的count的值是自增的,是独立的,互不影响。 vue代码: {{name}} {{count}} {{item}} new Vue({ components:{ "my-component-b":{ template:'#my-template', data(){ return{ name:'欢迎来到perfect*的博客园_01', numArray:[1,2,3,4,5], count:0 } } } } }).$mount('div');
html:
动态组件: 在一个元素上挂载多个组件,根据不同状态进行切换的时候,可以使用动态组件; 动态组件的使用: 需要使用内置组件,根据 :is 的值决定显示哪个组件,:is的值是要显示的组件id;
示例: 初始效果: 初始代码: ![]() ![]() perfect* " 37 38 }, 39 40 41 } 42 43 44 45 }).$mount('div'); 46 47 动态组件
现在的需求: 需要在页面中只显示一个,并通过三个button来进进行控制它们的显示
由效果图可知,页面默认显示my-component-a标签的内容
vue代码: new Vue({ data:{ selectName:'my-component-a' }, components:{ "my-component-a":{ template:'欢迎来到perfect*的博客园' }, "my-component-b":{ template:" perfect*的博客园 " }, "my-component-c":{ template:"perfect* " }, } }).$mount('div');html: a b c代码注意:
总的代码: ![]() ![]() perfect* " 46 47 }, 48 49 50 } 51 52 53 54 }).$mount('div'); 55 56 动态组件
动态组件结合keep-alive keep-alive:将非活动的组件缓存起来 include - 字符串或正则表达式。只有名称匹配的组件会被缓存。 exclude - 字符串或正则表达式。任何名称匹配的组件都不会被缓存。 max - 数字。最多可以缓存多少组件实例。 示例: 初始效果: 由图可以看出每一次点击button调用的值不一样,因此引入了keep-alive来进行缓存 ![]() ![]() C:{{num}} ", data(){ return{ num:Math.ceil(Math.random()*100) } } }, } }).$mount('div'); 初始代码
从图中可以看出 a:1 b:84 c: 86的值一直没发生改变,说明已经被缓存了。
include属性: 只有a的值被缓存了 可以通过数组进行多个: 效果: 缓存了a和b的值 同理exclude 属性测试方法和include一样,只是exclude表示的是除了那一个不缓存
max属性:最多可以缓存多少组件实例 效果图:
总的代码: ![]() ![]() C:{{num}} ", 64 data(){ 65 66 return{ 67 num:Math.ceil(Math.random()*100) 68 } 69 } 70 71 }, 72 73 74 } 75 76 77 78 }).$mount('div'); 79 80 动态组件结合keep-alive详细介绍官网网址: https://cn.vuejs.org/v2/api/#keep-alive
|
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |