Vue 全组件 局部组件

2024-03-01 1025阅读

温馨提示:这篇文章已超过397天没有更新,请注意相关的内容是否还可用!

一、组件定义和使用

1、全局组件

定义

   

       

This is a global component

   

 Vue 全组件 局部组件

导入

全局组件在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')

 Vue 全组件 局部组件

使用 

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

Vue 全组件 局部组件

2、局部组件

定义

Vue 全组件 局部组件

导入与使用

Vue 全组件 局部组件

二、组件通信

1、props

(1)传递单个值

Vue 全组件 局部组件

 Vue 全组件 局部组件

(2)传递多个值

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

Vue 全组件 局部组件

 Vue 全组件 局部组件

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

Vue 全组件 局部组件

 Vue 全组件 局部组件

2、插槽

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

(1)匿名插槽

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

Vue 全组件 局部组件

 Vue 全组件 局部组件

 Vue 全组件 局部组件

(2)具名插槽

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

 Vue 全组件 局部组件

 Vue 全组件 局部组件

 Vue 全组件 局部组件

(3)作用域插槽

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

子组件

   

       

This is a local component

       

   

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

 //父组件

 

   

This is a component view

   

     

     

        {{ slotProps.item }}*****{{ slotProps.index }}

     

   

 

//父组件写法二

 

   

This is a component view

   

     

     

        {{ item }}*****{{ index }}

     

   

 

 

3、provide&inject

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

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

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

//父组件

 

   

 

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

import { provide, ref } from "vue";

const msg = ref('hello world');

provide('msg',msg);

 //子组件

   

        LocalComponent

       

   

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

 //孙子组件

   

       

This is a GrandChild component

        {{ msg }}

   

import { inject } from "vue";

const msg = inject('msg');

4、事件通信

 

三、异步组件

VPS购买请点击我

免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们,邮箱:ciyunidc@ciyunshuju.com。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

目录[+]