在uni-app中,组件通信是十分重要的知识,为我们的前端页面发提供了十分的便利!
1.首先我们先说一下什么是组件
组件 (Component) 是 Vue.js 最强大的功能之一。组件可以进行数据传递、扩展 HTML 元素以及封装可重用的代码。在较高层面上,组件是自定义元素,Vue.js 的编译器为它添加特殊功能。在有些情况下,组件也可以表现为用 is 特性进行了扩展的原生 HTML 元素。
简而言之,组件就是封装好的一些代码,可以循环使用
2.建立一个组件
我们先来看一看什么是子组件想父组件传值
(1)首先创建一个uni-app项目,命名为text吧,这里我们选着vue3
(2)在uni-app里面新建一个目录,命名components(组件),在其里面创建一个子组件命名为comp,定义<template></template>模板
(3)因为是子向父传值,这里我们使用一个按钮来掩饰,同时我们通过¥emit()来传递值(第一个是方法名,第二个是要传的值)下面是基本的代码
(4)在写完子组件后,我们要在uni-app目录下的pages里面的index接受值,通过import调用子组件,再通过components注册一下,下面展示:
(5)在写好基本的连接后,在view class = content里面写<comp @Data = "getText"></comp>,这样就时子组件的的信息传过来啦
(6)通过console.log()打印一下
(7)运结果如下:
3.然后我们再来看一看,怎样可以实现父向子传值呢
(1)在现在的index中,在data里面声明以一个量,这里起名为name吧
(2)通过<comp @Data = "getText"></comp>标签,绑定name<comp :naem="name" @Data = "getText"></comp>
(3)让后返回父组件里,通过props接受值,这里我们通过 console.log()打印一下this.name
(4)运行结果如下:
好了,以上就是一个简单的父子通信,大家可以理解一下,在进行多数据,或以列表的形式进行传值,真正提高网页开发效率
下面是源代码
<template>
<view class="content">
<button type="primary" @click="textData">发送</button>
</view>
</template>
<script>
//这是子组件comp
export default {
props:{
name: String
},
data() {
return {
}
},
methods:{
textData(){
//子传父
this.$emit('Date',"这是一个子组件,"+this.name);
}
}
}
</script>
<style>
</style>
<template>
<view class="content">
<image class="logo" src="/static/logo.png"></image>
<view class="text-area">
<text class="title">{{title}}</text>
</view>
<comp @Date="getText"></comp>
</view>
</template>
<script>
//这是父组件index
import comp from'../../components/comp.vue'
export default {
components: {
comp
},
data() {
return {
title: 'Hello',
name:'你好uni'
}
},
onLoad() {
},
methods: {
getText(Data){
console.log(Data)
}
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.logo {
height: 200rpx;
width: 200rpx;
margin-top: 200rpx;
margin-left: auto;
margin-right: auto;
margin-bottom: 50rpx;
}
.text-area {
display: flex;
justify-content: center;
}
.title {
font-size: 36rpx;
color: #8f8f94;
}
</style>