动态组件 和 异步组件
1 动态组件
动态组件就是 component组件 ,组件身上可以绑定一个is属性, 用来表示某一个组件。
通过使用保留的元素,动态地绑定到它的 is 特性,我们让多个组件可以使用同一个挂载点,并动态切换。根据 v-bind:is=“组件名” 中的组件名去自动匹配组件,如果匹配不到则不显示。
1.1 使用方式
1.1.1 动态组件
局部注册:
// 方式一:
<template>
<component :is="myComponent"></component>
<button @click="switchCmp">切换组件</button>
</template>
<script>
import myComponent1 from '../my-component1'; // 引入方式1
import myComponent2 from '../my-component2';
export default {
components: { myComponent1, myComponent2 },
data() {
return {
myComponent: myComponent1
};
},
methods: {
switchCmp() {
this.myComponent = myComponent2;
}
}
};
</script>
// 方式二:
<template>
<component :is="myComponent"></component>
<button @click="switchCmp">切换组件</button>
</template>
<script>
export default {
components: {
myComponent1: () => import('./my-component1'), // 引入方式二
myComponent2: () => import('./my-component2')
},
data() {
return {
myComponent: myComponent1
};
},
methods: {
switchCmp() {
this.myComponent = myComponent2;
}
}
};
</script>
全局注册
// main.js
Vue.component('myComponent1', () => import('./my-component1')); // 引入方式3
Vue.component('myComponent2', () => import('./my-component2')); // 组件使用
<template>
<component :is="myComponent"></component>
<button @click="switchCmp">切换组件</button>
</template>
<script>
export default {
components: {
myComponent1,
myComponent2
},
data() {
return {
myComponent: myComponent1
};
},
methods: {
switchCmp() {
// 切换组件
this.myComponent = myComponent2;
}
}
};
</script>
1.1.2 对象
<template>
<component :is="myComponent"></component>
<button @click="switchCmp">切换组件</button>
</template>
<script>
export default {
data() {
myComponent: {
template: '<h1>默认显示组件:{{title}}</h1>',
data() {
return {
title: '组件1'
}
}
}
},
methods: {
switchCmp() {
this.myComponent = { // 使用方式4
template: '<h1>切换完显示的组件</h1>'
};
}
}
}
</script>
2 异步组件
在大型应用中,我们可能需要将应用分割成小一些的代码块,并且只在需要的时候才从服务器加载一个模块。为了简化,Vue 允许你以一个工厂函数(工厂函数是专门创建对象的函数)的方式定义你的组件,这个工厂函数会异步解析你的组件定义。Vue 只有在这个组件需要被渲染的时候才会触发该工厂函数,且会把结果缓存起来供未来重渲染。
定义异步组件
// 全局注册 - 工厂函数需要返回Promise对象, vue最终会将其转换为上面的对象形式
// 方式一
Vue.component('async-example', function(resolve, reject) {
// 返回一个promise对象
resolve({
template: '<div>I am async!</div>'
});
});
// 方式二
Vue.component(
'async-webpack-example',
// 这个动态导入会返回一个 `Promise` 对象。
() => import('./my-async-component')
);
// 局部
new Vue({
// 当使用局部注册的时候,你也可以直接提供一个返回 Promise 的函数
components: {
'my-component': () => import('./my-async-component')
}
});
3 关系
动态组件和异步组件之间的关系,总结一句话:
动态组件,使用 异步加载方式 来 加载异步组件