vue 在使用组件时,大部分都在使用同步组件和动态组件,少数部分使用 异步组件。
1. 动态组件 普通做法
背景:一个组件显示,另外一个组件隐藏,反之。
<script>
// 创建 vue实例
const app = Vue.createApp({
data() {
return {
currentItem: 'input-item'
}
},
methods:{
handleClick() {
if (this.currentItem === 'input-item') {
this.currentItem = 'common-item'
} else {
this.currentItem = 'input-item'
}
}
},
// 动态组件
template: `
<input-item v-show=" currentItem === 'input-item' "/>
<common-item v-show=" currentItem === 'common-item' "/>
<button @click="handleClick">切换</button>
`
});
// 自定义组件
app.component('input-item', {
template: `
<input />
`
});
app.component('common-item', {
template: `
<div> hello world</div>
`
});
const vm = app.mount('#root');
</script>
2. 动态组件 升级版
<script>
// 创建 vue实例
const app = Vue.createApp({
data() {
return {
currentItem: 'input-item'
}
},
methods:{
handleClick() {
if (this.currentItem === 'input-item') {
this.currentItem = 'common-item'
} else {
this.currentItem = 'input-item'
}
}
},
// 动态组件:根据 component这个标签,来随时动态切换组件
// 动态组件 使用 component 根据 参数currentItem 决定显示哪个控件
// <keep-alive> 缓存组件,会将组件内的数据进行缓存,下次使用时直接从缓存中获取
template: `
<keep-alive>
<component :is="currentItem" />
</keep-alive>
<button @click="handleClick">切换</button>
`
});
// 自定义组件
app.component('input-item', {
template: `
<input />
`
});
app.component('common-item', {
template: `
<div> hello world</div>
`
});
const vm = app.mount('#root');
</script>
3. 异步组件
<script>
// defineAsyncComponent
// Promise
// 异步
const asynvCommonItem = Vue.defineAsyncComponent(()=> {
return new Promise ((resolve, reject)=> {
setTimeout(() => {
resolve({
template: `
<div> asynvCommonItem </div>
`
})
}, 4000);
})
});
// 创建 vue实例
const app = Vue.createApp({
// 异步组件
// 异步组件:是异步执行某些组件的逻辑,这叫做异步组件
template: `
<div>
<common-item />
<async-common-item />
</div>
`
});
// 同步组件
app.component('common-item', {
template: `
<div> hello world</div>
`
});
// 异步组件
app.component('async-common-item', asynvCommonItem);
const vm = app.mount('#root');
</script>
vue 基础使用大致这些,下面会输出 vue和css 动画的一些操作。