在 vue中 做个类似聊天框的功能
看图 vue3添加文字追加文字段的时候看到滚动条 但是并没有自己去滚到最下面,很多聊天工具呢 点击send 默认都会到最新消息那 就是滚动条最下方
Vue 更i性能dom是异步的 数据更新是同步的
解决办法:1.回调函数模式 2.async await 写法
第一种解决办法:
javascript
<template>
<div style="padding: 180px">
<div
ref="box"
style="
height: 500px;
width: 500px;
border: 1px solid red;
overflow: auto;
"
>
<div
v-for="item in chatList"
style="
background-color: aquamarine;
border: 1px solid;
display: flex;
"
>
<p>{{ item.name }}</p>
<p>{{ item.message }}</p>
</div>
</div>
<div>
<textarea style="width: 500px" v-model="ipt" type="txt"></textarea>
</div>
<el-button @click="send">send</el-button>
</div>
</template>
<script setup lang="ts">
import { nextTick } from "vue"
import { ref, reactive } from "vue"
let chatList = reactive([{ name: "张三", message: "xxxxxx" }])
const ipt = ref("")
const box = ref<HTMLDivElement>()
// Vue 更i性能dom是异步的 数据更新是同步的
const send = () => {
chatList.push({ name: "小六", message: ipt.value })
// ipt.value=''
nextTick(() => {
box.value!.scrollTop = 99999
})
}
</script>
<style module lang="scss"></style>
第二种解决办法:
javascript
<template>
<div style="padding: 180px">
<div
ref="box"
style="
height: 500px;
width: 500px;
border: 1px solid red;
overflow: auto;
"
>
<div
v-for="item in chatList"
style="
background-color: aquamarine;
border: 1px solid;
display: flex;
"
>
<p>{{ item.name }}</p>
<p>{{ item.message }}</p>
</div>
</div>
<div>
<textarea style="width: 500px" v-model="ipt" type="txt"></textarea>
</div>
<el-button @click="send">send</el-button>
</div>
</template>
<script setup lang="ts">
import { nextTick } from "vue"
import { ref, reactive } from "vue"
let chatList = reactive([{ name: "张三", message: "xxxxxx" }])
const ipt = ref("")
const box = ref<HTMLDivElement>()
// Vue 更i性能dom是异步的 数据更新是同步的
// 解决办法:1.回调函数模式 2.async await 写法
const send = async () => {
chatList.push({ name: "小六", message: ipt.value })
ipt.value = ""
await nextTick()
box.value!.scrollTop = 99999
}
</script>
<style module lang="scss"></style>