今天在网上闲逛的时候,发现前端这几年的发展离不开组件这个概念。之前接触过的组件基本都是constapp=Vue.createApp({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'}},模板:`你好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:`//为了缓存文本框之前的数据HelloWorld
`})constvm=app.mount("#root")在编辑器的第一段代码中,引入自定义标签的组件后,可以直接显示效果,这种组件就变成了同步组件,当然还有异步组件,主要是解决首屏加载速度的问题,借助Vue3中的defineAsyncComponent,是这样的constAsyncCommonItem=Vue.defineAsyncComponent(()=>{returnnewPromise((resolve,reject)=>{setTimeout(()=>{resolve({template:'这是一个异步组件
'})},4000)})})constapp=Vue.createApp({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()},模板:`