目的:
1.掌握uni.request
2.掌握button @click点击事件
3.掌握v-model实现双向绑定
代码:
template区
<template>
<view class="vw1">
<view class="vw2">
<input class="ip1" placeholder="请输入要发送的信息" v-model="text"/>
<button class="bt1" type="primary" @click="click1">发送</button>
</view>
<view class="vw3" v-for="(item,index) in msglist"> //v-for循环遍历出聊天 内容
<text>{{item}}</text>
</view>
</view>
</template>
script区
<script>
export default {
data() {
return {
text:"", //用户输入框中输入的内容
msglist:[ ] //用于存放对话内容的列表
}
},
methods: {
click1(){ //定义一个click1函数来实现存入对话及api请求
this.msglist.push(this.text) //将输入框中内容传入存放对话的列表
uni.request({ //发起api请求
url:'https://apibug.cn/api/xiaoai/?msg='+this.text+'&apiKey=af4d2b71116c2ca96aa8411529a9c641',//将用户输入框中的内容放入api的url中
success:(res) => {
console.log(res.data)
this.text = '' //清空输入框,方便用户下次输入
this.msglist.push(res.data.text) //将机器人回复内容传入列表
}
})
}
}
}
</script>
style区
<style>
.ip1{
caret-color: #4e6ef2;
position: relative;
z-index: 17;
box-sizing: border-box;
display: block;
padding: 10px 20px;
margin: 0;
height: 48px;
line-height: 20px;
width: 336px;
border: 1px solid #b8b8b8;
font-size: 18px;
color: #1f1f1f;
transition: .3s;
font-family: PingFangSC-Regular,Tahoma,Helvetica,"Microsoft Yahei","微软雅黑",Arial,STHeiti;
border-radius: 8px;
margin-top: 50px;
}
.bt1{
width: 336px;
height: 48px;
line-height: 48px;
background: #4e6ef2;
border-radius: 10px;
box-shadow: 0 6px 16px 0 rgb(78 111 242 / 30%);
font-size: 17px;
font-weight: 800;
border: 0;
color: #fff;
cursor: pointer;
margin-top: 40px;
}
.vw1{
width: 100%;
height: 100%;
flex: ;
display: flex;
flex-direction: column;
justify-content: column;
align-items: center;
margin-top: 50px;
}
.vw2{
margin-bottom: 20px;
}
.vw3{
margin-top:7px;
}
</style>