1.动态组件
Vue.js 提供了一个特殊的元素
示例如下:
var app21 = new Vue({
el: '#app21',
data: {
currentView: 'comA'
},
methods: {
changeView: function(data){
this.currentView = 'com'+ data //动态地改变currentView的值就可以动态挂载组件了。
}
},
components: {
comA: {
template: '组件A'
},
comB: {
template: '组件B'
},
comC: {
template: '组件C'
}
}
});
2,递归组件
组件在它的模板内可以递归地调用自己, 只要给组件设置name 的选项就可以了。
示例如下:
Vue.component('my-component19',{
name: 'my-component19', //其实当你利用 Vue.component 全局注册了一个组件,全局的ID会被自动设置为组件的name。
props: {
count: {
type: Number,
default: 1
}
},
template: ' '
});
var app19 = new Vue({
el: '#app19'
});
渲染结果为:
设置name 后,在组件模板内就可以递归使用了,不过需要注意的是,必须给一个条件来限制递归数量,否则会抛出错误: max stack size exceeded 。
组件递归使用可以用来开发一些具有未知层级关系的独立组件,比如级联选择器和树形控件等。
3.组件卡槽solt
3.1 第一种用法
父组件
slot分发了内容
子组件
这是slot子组件
如果slot没有分发内容。
效果图如下:
我得理解,slot在父组件有内容时,显示为父组件得内容,覆盖了子组件,如果父组件没有内容,则显示子组件
3.2 第二种用法
这种用法是我们用得比较多得,这种是具名得slot
父组件
footer
header
Default content
子组件
效果图如下:
我把父组件的header和footer更换了位置,
是为了证明一件事,就是实际内容的显示是由子组件的位置决定的。
4. 异步组件:页面需要用到时候才从服务端加载的组件。
原理:利用webpack对代码进行分割是异步调用组件前提。下面介绍的是怎么实现异步组件。
案例:
首先是组件,创建四个组件分别命名为first、second、three和four;内容如下:
first
我是第一个页面
second
我是第二个页面
three
我是第三个页面
four
我是第四个页面
路由index.js代码,异步组件方式有两种,代码中的方案1和方案2;注意:方案1需要添加 syntax-dynamic-import
插件
import Vue from 'vue'
import VueRouter from 'vue-router'
/*import First from '@/components/First'
import Second from '@/components/Second'*/
Vue.use(VueRouter)
//方案1
const first =()=>import(/* webpackChunkName: "group-foo" */ "../components/first.vue");
const second = ()=>import(/* webpackChunkName: "group-foo" */ "../components/second.vue");
const three = ()=>import(/* webpackChunkName: "group-fooo" */ "../components/three.vue");
const four = ()=>import(/* webpackChunkName: "group-fooo" */ "../components/four.vue");
//方案2
const first = r => require.ensure([], () => r(require('../components/first.vue')), 'chunkname1')
const second = r => require.ensure([], () => r(require('../components/second.vue')), 'chunkname1')
const three = r => require.ensure([], () => r(require('../components/three.vue')), 'chunkname2')
const four = r => require.ensure([], () => r(require('../components/four.vue')), 'chunkname2')
//懒加载路由
const routes = [
{ //当首次进入页面时,页面没有显示任何组件;让页面一加载进来就默认显示first页面
path:'/', //重定向,就是给它重新指定一个方向,加载一个组件;
component:first
},
{
path:'/first',
component:first
},
{
path:'/second',
component:second
}, {
path:'/three',
component:three
},
{
path:'/four',
component:four
}
//这里require组件路径根据自己的配置引入
]
//最后创建router 对路由进行管理,它是由构造函数 new vueRouter() 创建,接受routes 参数。
const router = new VueRouter({
routes
})
export default router;