手拉手Vue组件由浅入深

2024-01-18 09:36

本文主要是介绍手拉手Vue组件由浅入深,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

组件 (Component) 是 Vue.js 最强大的功能之一,它是html、css、js等的一个聚合体,封装性和隔离性非常强。

组件化开发:
    1、将一个具备完整功能的项目的一部分分割多处使用
    2、加快项目的进度
    3、可以进行项目的复用

组件注册分为:全局注册和局部注册

目录

Vue组件

组件的生命周期钩子

组件嵌套关系

组件注册

组件数据传递props

传递数组,对象

类型验证

Props实现子传父

组件数据传递$emit

组件+v-model

透传

动态组件

​编辑

​编辑

异步组件

依赖注入-透传


Vue组件

组件的优点:可复用性

组件构成

<template></template><script>export default{}</script><style></style>

组件引入

组件的生命周期钩子

每个 Vue 组件实例在创建时都需要经历一系列的初始化步骤,比如设置好数据侦听,编译模板,挂载实例到 DOM,以及在数据改变时更新 DOM。在此过程中,它也会运行被称为生命周期钩子的函数,让开发者有机会在特定阶段运行自己的代码

创建期:beforeCreate、created

挂载期:beforeMount 、mounted

更新期:beforeUpdate、updated

销毁期:beforeUnmount 、unmountd

<script>
export default{
beforeCreate(){console.log("创建之前")
},
created(){console.log("创建之后")},
beforeMount(){console.log("挂载之前")
},mounted(){console.log("挂载之后")
},beforeUpdate(){console.log("更新之前")
},updated(){console.log("更新之后")
},beforeUnmount(){console.log("销毁之前")
},unmountd(){console.log("销毁之后")
}
}
</script>

组件嵌套关系

组件允许将ui划分为独立的、可重用的部分,并且可以对每个部分进行单独的思考。在实际项目中,组件是层层嵌套的树形结构,每个组件内封装自定义内容与逻辑。

取消main.css依赖

Article.vue

<template><H3>Article</H3>
</template><style scoped>
h3{width: 80%;margin: 0 auto;text-align: center;line-height: 100px;box-sizing: border-box;margin-top: 25px;background: #bdbaba;    
}</style>

Item.vue
 

<template><H3>Item</H3>
</template><style scoped>h3{width: 80%;margin: 0 auto;text-align: center;line-height: 100px;box-sizing: border-box;margin-top: 25px;background: #bdbaba;    
}</style>

Hrader.vue

<template><H3>Header</H3>
</template><style scoped>h3{width: 100%;height: 100px;border: 5px solid #999;text-align: center;line-height: 100px;box-sizing: border-box;}
</style>

Main.vue

<template><div class="main"><H3>Main</H3>    <Article/><Article/><Article/></div></template><script>import Article from "./article.vue"
export default{components:{Article}
}</script><style scoped>.main{float: right;width: 85%;height: 500px;border: 5px solid #999;box-sizing: border-box;text-align: center;
}</style>

Aside.vue

<template><div class="aside"><H3>Aside</H3><Item/>  <Item/><Item/></div></template><script>
import Item from './Item.vue';
export default{components:{Item}}</script><style scoped>.aside{float: left;width: 14%;height: 500px;border: 5px solid #999;box-sizing: border-box;text-align: center;
}</style>

效果

组件注册

局部注册(建议使用)

在一个组件中进行注册

全局注册

在main.js中全局注册

全局注册很方便,但是在全局注册中,没有被使用的组件无法在生成打包的时候被自动移除(“tree-shaking”),依然出现在打包后的js文件中。

在项目嵌套较多的时候,全局注册的依赖关系不明确,可能影响应用长期维护性。

组件数据传递props

组件之间是可以传递数据,而传递数据的解决方案是props,注:props传递数据只能父级传递子级。

组件传递的数据类型:数字、对象、数字等。任何类型的值都可以作为props的值传递

组件间传递数据应用场景: 父传子

Parent.vue

<template><h3>Parent</h3><input v-model="msg"><Child :title="msg" test="数据"/>
</template><script>
import Child from './Child.vue';
export default{data(){return{msg:""}},components:{Child}
}</script>

Child.vue

<template><h3>Child</h3><p> {{ title }} </p><p>{{ test }}</p></template><script>
export default{data(){return{}},//接收数据props:["title","test"]
}</script>

传递效果

传递数组,对象

Parent.vue

<template><h3>Parent</h3><input v-model="msg"><Child :title="msg" test="数据" :names="names" :user="user" :number1="number1"/>
</template><script>
import Child from './Child.vue';
export default{data(){return{msg:"",names:["张三","李四","王五"],user:{name:"张三",age:20},number1:123}},components:{Child}
}</script>

Child.vue

<template><h3>Child</h3><p> {{ title }} </p><p>{{ test }}</p><p v-for="(name,index) of names" :key="index">{{ index }} : {{ name }}</p><p>{{ user.name }} {{ user.age }}</p>
</template><script>
export default{data(){return{}},//接收数据props:["title","test","names","user"]}</script>

传递对象

类型验证

<template><h3>Child</h3><p> {{ title }} </p><p>{{ test }}</p><p v-for="(name,index) of names" :key="index">{{ index }} : {{ name }}</p><p>{{ user.name }} {{ user.age }}</p></template><script>
export default{data(){return{}},//接收数据props:{title:{type:[String,Number,Array,Object]},names:{type:Array},user:{type:Object,//必选项required:true},test:{type:String},number:{type:Number,default:0}}}
</script>

Props实现子传父

组件数据传递$emit

组件模板表达式中,可以使用$emit方法触发自定义事件

组件间传递数据应用场景:子传父

Child.vue

<template>Child<button @click="clickEventHandle">向父组件发送数据</button></template><script>
export default{data(){return{msg:"传递数据"}},methods:{clickEventHandle(){this.$emit("eventDemo",this.msg)}}}</script>

Parent2.vue

<template>
<Child @eventDemo="getHandle"/>
</template>
<script>
import Child from "./Child.vue"
export default {components:{Child},methods:{getHandle(data){console.log(data)}}
}</script>

组件+v-model

查询:<input type="text" v-model="search">

watch:{search(newValue,oldValue){this.$emit("searchEvent",newValue)}},

透传

透传attribute指的是传递给一个组件,没有被该组件声明为props或emits的arrtibute或者v-on事件监听器。最常见的例子就是class、id、style。

一个组件以单个元素为根做渲染时,透传的attribute会自动被添加到根元素上

App.vue

Attr.vue

<template><h2>透传属性测试</h2>
</template><style>
.colorDemo{color: aqua;
}
</style>

效果

禁用透传attribute

export default{inheritAttrs:false
}

动态组件

<template>
<component :is="tabComponent"></component>
<button @click="changeComponent">切换组件</button>
</template><script >
import ComponentsA from "./components/ComponentsA.vue"
import ComponentsB from "./components/ComponentsB.vue"
export default{data(){return{tabComponent:"ComponentsA"}},methods:{changeComponent(){// 三元运算符this.tabComponent= this.tabComponent =="ComponentsA"? "ComponentsB" : "ComponentsA"}}

当使用<component :is="tabComponent"></component>在多个组件间切换时,被切换掉的组件会被卸载。可以通过<keep-alive>组件前置被切换掉的组件依然保持“存活状态”

<KeepAlive>
<component :is="tabComponent"></component>
</KeepAlive>

异步组件

Vue提供了defineAsyncComponent实现异步组件功能。

import ComponentsA from "./components/ComponentsA.vue"
//异步加载组件
const ComponentsB =defineAsyncComponent(()=>import("./components/ComponentsB.vue")
).catch(function(error){console.log(error);
})


异步组件的优势
1.减少应用程序的初始加载时间
异步组件只有在需要使用该组件时才会进行加载,可以减少应用程序的初始加载时间,提高用户体验。
2.提高应用程序的性能
异步组件可以将组件的加载和渲染分开进行,可以提高应用程序的性能,避免不必要的渲染。
3.优化代码的可维护性
异步组件可以将组件按需加载,可以优化代码的可维护性,减少代码的复杂度。

异步组件的注意事项

1.异步组件的加载时间
异步组件是按需加载的,因此在使用异步组件时,需要考虑组件的加载时间。如果组件的加载时间过长,会对应用程序的性能和用户体验产生影响。
2.异步组件的错误处理
在使用异步组件时,需要对组件加载过程进行错误处理,避免出现错误导致应用程序无法运行。可以通过 catch() 方法来捕获异步加载组件时的错误。

依赖注入-透传

prop逐级透传可以用provide和inject解决这一问题。一个父组件相对于其所有的子组件,会作为依赖提供者。任何子组件树,无论层级多深,都可以注入由父组件提供给整条链路的依赖

App.vue

<template><Parent/></template><script >
import Parent from "./components/Parent.vue"export default{provide:{messages:"app组件"},}
</script>

Parent.vue

<template><h3>Parent</h3><Child></Child></template>

Child.vue

<template>Child
<p>{{ messages }}</p>
</template><script>
export default{inject:["messages"],}
</script>

效果

动态穿透

<template><Parent/></template><script >import Parent from "./components/Parent.vue"
provide(){return{messages: this.messages}},data(){return{messages:"app组件"}},
</script>

全局数据

app.provide("golabData","全局数据")

这篇关于手拉手Vue组件由浅入深的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/618642

相关文章

Vue3 的 shallowRef 和 shallowReactive:优化性能

大家对 Vue3 的 ref 和 reactive 都很熟悉,那么对 shallowRef 和 shallowReactive 是否了解呢? 在编程和数据结构中,“shallow”(浅层)通常指对数据结构的最外层进行操作,而不递归地处理其内部或嵌套的数据。这种处理方式关注的是数据结构的第一层属性或元素,而忽略更深层次的嵌套内容。 1. 浅层与深层的对比 1.1 浅层(Shallow) 定义

JS常用组件收集

收集了一些平时遇到的前端比较优秀的组件,方便以后开发的时候查找!!! 函数工具: Lodash 页面固定: stickUp、jQuery.Pin 轮播: unslider、swiper 开关: switch 复选框: icheck 气泡: grumble 隐藏元素: Headroom

这15个Vue指令,让你的项目开发爽到爆

1. V-Hotkey 仓库地址: github.com/Dafrok/v-ho… Demo: 戳这里 https://dafrok.github.io/v-hotkey 安装: npm install --save v-hotkey 这个指令可以给组件绑定一个或多个快捷键。你想要通过按下 Escape 键后隐藏某个组件,按住 Control 和回车键再显示它吗?小菜一碟: <template

【 html+css 绚丽Loading 】000046 三才归元阵

前言:哈喽,大家好,今天给大家分享html+css 绚丽Loading!并提供具体代码帮助大家深入理解,彻底掌握!创作不易,如果能帮助到大家或者给大家一些灵感和启发,欢迎收藏+关注哦 💕 目录 📚一、效果📚二、信息💡1.简介:💡2.外观描述:💡3.使用方式:💡4.战斗方式:💡5.提升:💡6.传说: 📚三、源代码,上代码,可以直接复制使用🎥效果🗂️目录✍️

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06

如何在页面调用utility bar并传递参数至lwc组件

1.在app的utility item中添加lwc组件: 2.调用utility bar api的方式有两种: 方法一,通过lwc调用: import {LightningElement,api ,wire } from 'lwc';import { publish, MessageContext } from 'lightning/messageService';import Ca

计算机毕业设计 大学志愿填报系统 Java+SpringBoot+Vue 前后端分离 文档报告 代码讲解 安装调试

🍊作者:计算机编程-吉哥 🍊简介:专业从事JavaWeb程序开发,微信小程序开发,定制化项目、 源码、代码讲解、文档撰写、ppt制作。做自己喜欢的事,生活就是快乐的。 🍊心愿:点赞 👍 收藏 ⭐评论 📝 🍅 文末获取源码联系 👇🏻 精彩专栏推荐订阅 👇🏻 不然下次找不到哟~Java毕业设计项目~热门选题推荐《1000套》 目录 1.技术选型 2.开发工具 3.功能

Vue3项目开发——新闻发布管理系统(六)

文章目录 八、首页设计开发1、页面设计2、登录访问拦截实现3、用户基本信息显示①封装用户基本信息获取接口②用户基本信息存储③用户基本信息调用④用户基本信息动态渲染 4、退出功能实现①注册点击事件②添加退出功能③数据清理 5、代码下载 八、首页设计开发 登录成功后,系统就进入了首页。接下来,也就进行首页的开发了。 1、页面设计 系统页面主要分为三部分,左侧为系统的菜单栏,右侧

【VUE】跨域问题的概念,以及解决方法。

目录 1.跨域概念 2.解决方法 2.1 配置网络请求代理 2.2 使用@CrossOrigin 注解 2.3 通过配置文件实现跨域 2.4 添加 CorsWebFilter 来解决跨域问题 1.跨域概念 跨域问题是由于浏览器实施了同源策略,该策略要求请求的域名、协议和端口必须与提供资源的服务相同。如果不相同,则需要服务器显式地允许这种跨域请求。一般在springbo

HTML提交表单给python

python 代码 from flask import Flask, request, render_template, redirect, url_forapp = Flask(__name__)@app.route('/')def form():# 渲染表单页面return render_template('./index.html')@app.route('/submit_form',