当前位置: 首页 > Web前端 > JavaScript

Vue3的动态组件和异步组件

时间:2023-03-27 13:31:15 JavaScript

今天在网上闲逛的时候,发现前端这几年的发展离不开组件这个概念。之前接触过的组件基本都是constapp=Vue.createApp({template:``})app.component('input-item',{template:`

`})app.component('common-item',{template:`
HelloWorld
`})constvm=app.mount("#root")这时候页面上会显示一个文本框和一行文字。这时候如果我们想通过一个按钮,来切换两个元素之间的真实和隐藏关系,可以将代码修改成这样constapp=Vue.createApp({data(){return{currentItem:'input-item'}},方法:{handleClick(){if(this.currentItem==='input-item'){this.currentItem='common-item'}else{this.currentItem='input-item'}//也可以通过三元运算符来实现,也可以参考绑定类或者样式绑定//this.currentItem=this.currentItem==='input-item'?'common-item':'input-item'}},模板:`切换`})app.component('input-item',{template:`
`})app.component('common-item',{template:`
你好World
`})constvm=app.mount("#root")有了动态组件,同样的需求我们的代码可以这样写//动态组件:根据数据变化,结合组件标签,随时动态切换组件的实现constapp=Vue.createApp({data(){return{currentItem:'input-item'}},methods:{handleClick(){if(this.currentItem==='input-item'){this.currentItem='common-item'}else{this.currentItem='input-item'}}},template:`//为了缓存文本框之前的数据切换`})app.component('input-item',{template:`
`})app.component('common-item',{template:`
HelloWorld
`})constvm=app.mount("#root")在编辑器的第一段代码中,引入自定义标签的组件后,可以直接显示效果,这种组件就变成了同步组件,当然还有异步组件,主要是解决首屏加载速度的问题,借助Vue3中的defineAsyncComponent,是这样的constAsyncCommonItem=Vue.defineAsyncComponent(()=>{returnnewPromise((resolve,reject)=>{setTimeout(()=>{resolve({template:'
这是一个异步组件
'})},4000)})})constapp=Vue.createApp({template:`
`})app.component('common-item',{template:`
HelloWorld
`})app.component('async-common-item',AsyncCommonItem)constvm=app.mount("#root")当然,今天我也为大家准备了一些其他常用的知识点,当饭后甜点吃就好了。使用这种方法,后期维护起来会很麻烦constapp=Vue.createApp({data(){return{count:1}},mounted(){//只挂载本生命周期较早的元素或较晚的console。log(this.$refs.countele)//
1
this.$refs.commele.sayHello()},模板:`{{count}}
`})app.component('common-item',{methods:{sayHello(){alert('hello')}},template:`
HelloWorld
`})constvm=app.mount("#root")2.privateinject:使用组件之间传递数据的方式和子组件的子组件,当我们将数据从组件传递给子组件的子组件时,我们可以constapp=Vue.createApp({data(){return{count:1}},template:`
`})app.component('child',{props:['count'],template:`
`})app.component('child-child',{props:['count'],template:`
{{count}}
`})constvm=app.mount("#root")显然,这样很麻烦,通过privateinject,我们可以写constapp=Vue.createApp({data(){return{count:1}},//provide:{//不能直接调用data中的数据,需要的时候需要写成一个函数//count:1//},//这个是一次性的,可以通过Vue3的getter方法响应,也可以通过传统的propsprovide(){return{count:this.count}},template:`
增加
`})app.component('child',{template:`
`})app.component('child-child',{inject:['count'],template:`
{{count}}
`})constvm=app.mount("#root")也可以扫描二维码关注我微信公众号,蜗牛全栈