Vue 全组件 局部组件

一、组件定义和使用

1、全局组件

定义

<template>

<div>

<h1>This is a global component</h1>

</div>

</template>

<script lang="ts">

</script>

<style></style>

导入

全局组件在main.ts(Vue + TS的项目)引入,

或者在main.js(Vue + JS的项目)引入

import { createApp } from 'vue'

import App from './App.vue'

import router from './router'

import store from './store'

import GlobalComponent from "../src/components/component/GlobalComponent.vue";

const app = createApp(App)

app.component("GlobalComponent",GlobalComponent);

app.use(store).use(router).mount('#app')

使用

全局组件可以在任意组件中使用,不需要再次导入

2、局部组件

定义

导入与使用

二、组件通信

1、props

(1)传递单个值

(2)传递多个值

如果传递的时对象,对象在被子组件的props接收时需要解构,依次写在props数组中

传递的如果是一个个的值,则直接在props数组中写入即可

2、插槽

插槽的作用:让子组件可以接收父组件传过来的元素、组件

(1)匿名插槽

如果父元素只传递一个元素,或者传递的多个元素会在一个地方使用,那么可以使用匿名插槽

(2)具名插槽

父组件会传递多个元素,这些元素需要再不同的地方使用,这时需要使用具名插槽进行区分

(3)作用域插槽

父组件需要用到子组件中的数据时,可以使用作用域插槽将子组件的数据传递过去

子组件

<template>

<div>

<h1>This is a local component</h1>

<slot v-for="(item,index) in list" :item="item" :index="index"/>

</div>

</template>

<script lang="ts" setup>

const list = [1,2,3,4];

</script>
//父组件

<template>

<div>

<h1>This is a component view</h1>

<div>

<GlobalComponent />

<LocalComponent v-slot="slotProps">

<div>{{ slotProps.item }}*****{{ slotProps.index }}</div>

</LocalComponent>

</div>

</div>

</template>
//父组件写法二

<template>

<div>

<h1>This is a component view</h1>

<div>

<GlobalComponent />

<LocalComponent v-slot="{item,index}">

<div>{{ item }}*****{{ index }}</div>

</LocalComponent>

</div>

</div>

</template>

3、provide&inject

父组件给子组件传值,子组件使用props接收,如果孙子组件乃至重孙子组件要使用父组件的数据,那么就要一层层用props传递,特别麻烦。

父组件使用provide(提供)提供数据

子组件、孙子组件、重孙子组件....可以使用inject接收数据

//父组件

<template>

<div>

<LocalComponent />

</div>

</template>

<script setup lang="ts">

import LocalComponent from "../components/component/LocalComponent.vue";

import { provide, ref } from "vue";

const msg = ref('hello world');

provide('msg',msg);

</script>
//子组件

<template>

<div>

LocalComponent

<GrandChild />

</div>

</template>

<script lang="ts" setup>

import GrandChild from '../component/GrandChild.vue';

</script>
//孙子组件

<template>

<div>

<h1>This is a GrandChild component</h1>

{{ msg }}

</div>

</template>

<script lang="ts" setup>

import { inject } from "vue";

const msg = inject('msg');

</script>

<style></style>

4、事件通信

三、异步组件

相关推荐
110546540126 分钟前
11、参数化三维产品设计组件 - /设计与仿真组件/parametric-3d-product-design
前端·3d
爱笑的林羽31 分钟前
Mac M系列 安装 jadx-gui
前端·macos
运维@小兵37 分钟前
vue使用路由技术实现登录成功后跳转到首页
前端·javascript·vue.js
肠胃炎39 分钟前
React构建组件
前端·javascript·react.js
酷爱码1 小时前
HTML5表格语法格式详解
前端·html·html5
hello_ejb31 小时前
聊聊JetCache的缓存构建
java·前端·缓存
堕落年代1 小时前
SpringSecurity当中的CSRF防范详解
前端·springboot·csrf
美酒没故事°1 小时前
纯css实现蜂窝效果
前端·javascript·css
GISer_Jing2 小时前
React useState 的同步/异步行为及设计原理解析
前端·javascript·react.js
mini榴莲炸弹2 小时前
什么是SparkONYarn模式?
前端·javascript·ajax