学习思考
💬vue脚手架与组件开发
00 分钟
2024-1-21
2024-1-23
type
status
date
slug
summary
tags
category
icon
password

1、脚手架

1.1 脚手架命令

VUE CLI ,vue官方基于webpack打造的脚手架工具,内置,会提供很多模板和工具。
可以帮助我们进行快速地创建vue项目。
notion image
安装环境:node、npm
notion image
npm,node包管理器,相当于一个应用商店。
npm i @vue/cli -g
i:install的意思
  • g:表示在node全局进行安装
vue create my-vue-project
通过vue cli方式来创建项目,
可以手动选择版本。
也可以用vue ui的命令来创建项目:
不常用,略过。。

1.2 脚手架创建后的项目结构

notion image
notion image
  • serve:可以打开一个本地的静态资源服务器,将项目直接跑起来。=> npm run serve
  • build:代码打包,=>npm run build
notion image
项目上线,使用的就是dist文件夹。
运行dist:
notion image
/开头,说明不是本地文件,需要用服务器的方式来启动。
要先运行下面这个命令,安装:
npm i serve -g
再运行:serve dist
notion image
效果一模一样:
notion image
其他的:
notion image
notion image
notion image
notion image
该目录用来保存自定义组件。
app.vue是根组件。
main.js是vue应用的一个入口文件。
notion image
notion image
那些配置文件内容大概如下:
notion image
notion image
notion image
notion image
notion image
 
  • ------------------------------------------------------------------------------------
2、组件化开发
2.1 组件的作用与本质
notion image
组件:用来封装页面部分功能的一种方式。
notion image
notion image
notion image
一个组件可以封装一块功能的结构、样式、逻辑。
每个.vue文件中都包含这几部分。
notion image
notion image
当一个组件定义好之后,怎么使用呢?
notion image
也可以写成多标签形式:
notion image
notion image
根组件,即App.vue有el,是有个挂载电;
而非根组件的位置,就是标签的位置。
2.2 组件的通信方式
notion image
组件与组件之间的关联性,就是说他们的数据交互。
A、父传子
=>父组件传值给子组件,让子组件根据自己的要求渲染自己的数据。
notion image
  • props来自于英文单词"properties"的缩写。在Vue中,props用于在父组件中向子组件传递数据,子组件通过props属性来声明接收的数据。
  • props是写在子组件上的;
  • 也可以绑定多个值
  • 用多个类型来定义
  • 子组件上可以设置默认值,如果父组件也传值,就用父组件的,如果父组件不传值,那就用子组件的默认值。
notion image
  • 也可以要求父组件必须传值;
notion image
父组件调用时,属性也可以用响应式数据:
notion image
notion image
B、子传父
notion image
下面的图来自于chatGPT:
子组件向父组件传递数据:通过$emit触发事件,父组件通过监听这个事件来接收数据。
notion image
在这个例子中,子组件通过$emit方法触发了一个名为childEvent的事件,并传递了一条消息。父组件通过监听childEvent事件,接收到了这条消息
notion image
notion image
然后在父组件做一个监听:
notion image
notion image
notion image
C、同级传值
来自 chatgpt:
在Vue2中,同级组件之间的通信可以通过以下几种方式传递值:
  1. 使用一个共享的父组件来传递数据:可以将需要传递的数据放在共享的父组件中,然后通过props属性将数据传递给同级组件。
  1. 使用事件总线:可以通过创建一个空的Vue实例作为事件总线,然后在同级组件中使用emit和on来进行事件的触发和监听。
吴悠大佬推荐的:
notion image
2.3 组件插槽
notion image
Vue2的组件插槽(Slot)是一种用于在组件中扩展内容的机制。它允许你在组件的模板中定义一些占位符,然后在使用该组件时,可以将内容插入到这些占位符中。
英文定义:Component Slots
组件插槽的作用是解决组件的可复用性和灵活性问题。它允许组件的使用者在不修改组件源代码的情况下,根据自己的需求来定制组件的部分内容。
让我们通过一个生活中的场景来说明组件插槽的用法。假设我们有一个通用的模态框(Modal)组件,用于显示各种弹窗内容。但是,不同的弹窗内容可能会有所不同,例如登录弹窗和注册弹窗。
使用组件插槽,我们可以在模态框组件中定义一个插槽,用于接收弹窗内容。然后,在使用模态框组件时,我们可以将具体的弹窗内容插入到这个插槽中。
2.3.1 默认插槽
36:33
notion image
notion image
 
  • 比props传值简单
  • 通过插槽方式,写成双标签的方式,可以实现更多的效果。
2.3.2 具名插槽
当组件里面有好几个地方可以让外部通过插槽传值的话,就需要取名。
notion image
notion image
效果如下:
notion image
也可以简写:#具名插槽名
notion image
除了插槽一些文本设置外,还可以在插槽里面使用子组件的一些数据:
是helloworld组件的数据,不是父组件里面的数据。
子组件给插槽传的是一个对象:dataObj
notion image
也可以使用解构方法取值:
notion image
 
 

评论
  • Twikoo