vue知识点总结 依赖注入 动态组件 异步加载
一 依赖注入
使用场景:当需要多层组件需要传值 如 祖宗-》父亲-》儿子-》孙子如祖宗的数据需要直接传给孙子
在祖宗组件中写:
data(){return {}}
provide(){
return {shujukey:'数据值'
}
}
在孙子组件中接收,模板代码中直接使用{{shujukey}}
获取数据
data(){return {}}
inject:['shujukey']
如果想全局使用某个依赖数据,需要在main.js中修改代码createApp(App).mount('#app')
为
const app=createApp(App);
app.provide('zuzongName','zuzongvalue')
app.mount('#app')
二 动态组件 异步加载
dom中
<component :is="mycomponent"></component><button @click="turntab">切换组件</button>
js中
import componentA from "./componentA.vue";
// import componentB from "./componentB.vue";
const componentB = defineAsyncComponent(() => import("./componentB.vue"));//异步加载data(){mycomponent:'componentA'
},
methods:{
turntab(){this.mycomponent =this.mycomponent === "componentA" ? "componentB" : "componentA";
}
}
如在切换组件的过程中不想叫组件销毁,可以使用
保持组件存活
<keep-alive><component :is="mycomponent"></component>
</keep-alive>