-
上编是微信界面(一),界面如下
image.png
-
这篇文章的目标页面如下:
image.png
- 在输入框输入内容,马上再页面上展示
代码
- 左侧的聊天记录展示界面组件代码(
ChatWindow.vue
)
<template>
<div class="chat">
<h3>用户聊天界面</h3>
<p>用户:{{currentUser.username}}</p>
<div class="chatlist">
<!--聊天记录内容列表展示 -->
<chatItemCom v-for="(item,index) in chatlist" :key="'chatlist'+index" :chatitem="item">
<!-- 传给插槽的内容-->
{{item.chatcontent}}
</chatItemCom>
</div>
<!--输入内容组件,绑定父元素的发送方法,触发后就是子组件发送内容给父组件-->
<ChatInputCom :sendEvent="sendEvent"></ChatInputCom>
</div>
</template>
<style scoped>
.chat
{
width: 500px;
}
</style>
<script>
// 输入内容,发送内容组件
import ChatInputCom from './ChatInputCom'
// 输入内容后展示内容后的组件
import chatItemCom from './chatItemCom'
export default {
components: {
ChatInputCom,chatItemCom
},
data() {
return {
chatlist:[
// {
// user:{
// username: "小明",
// headimg:require("../assets/images/1.jpg"),
// },
// chatcontent: "你好啊"
// }
]
}
},
props:["currentUser"],
methods:{
// 父元素传给子组件ChatInputCom,子组件触发父元素的方法,
//然后把chatcontent的值传给父元素,父元素把内容新增到chatlist中,chatlist就是内容展示组件chatItemCom的数据列表
sendEvent:function(value){
this.chatlist.push({
user:{
username: "小明",
headimg:require("../assets/images/1.jpg"),
},
chatcontent: value
}
)
}
}
}
</script>
-
ChatInputCom
输入内容并发送组件
<!-- 发送消息组件-->
<template>
<div class="chatinput">
<input type="text" @keydown.enter="send" v-model="inputContent" />
<!-- <input type="text" @keydown.enter="sendEvent($event.target.value)" v-model="inputContent" /> -->
<button @click="send">发送</button>
</div>
</template>
<script>
export default {
data() {
return {
inputContent:"",
}
},
//绑定父元素传过来的方法
props:["sendEvent"],
methods:{
send:function(){
this.sendEvent(this.inputContent)
this.inputContent = ""
}
}
}
</script>
-
chatItemCom.vue
聊天内容列表展示组件
<!--聊天内容记录-->
<template>
<div class="chatitem">
<!-- 注意style绑定的知识点-->
<img :style="imgStyle" :src="chatitem.user.headimg" alt="头像" />
<div>
<!--用插槽展示内容-->
<slot></slot>
</div>
</div>
</template>
<style scoped>
/* .chatitem img{width:80;height: 80px;} */
.chatitem {display: flex;}
</style>
<script>
export default {
data() {
return {
imgStyle:{
width: "60px",
height:"60px"
}
}
},
props:["chatitem"]
}
</script>
网友评论