返回
Vue打造的小Q机器人!开发者的福音!
前端
2023-10-10 16:32:05
Vue打造的小Q机器人(二)
[GitHub项目链接:https://github.com/baiyuliang/Qrobot_Vue]
项目完整结构:
- main.js
- App.vue
- Qrobot.vue
- styles.css
- package.json
- package-lock.json
接下来,开始着手修改刚刚创建完成的项目!
打开main.js,引入相关插件,本项目的网络请求依赖axios库:
import Vue from 'vue'
import App from './App.vue'
import Qrobot from './Qrobot.vue'
import axios from 'axios'
Vue.config.productionTip = false
Vue.prototype.axios = axios
new Vue({
render: h => h(App),
}).$mount('#app')
在Qrobot.vue文件中,构建小Q机器人组件:
<template>
<div class="qrobot">
<div class="qrobot-container">
<div class="qrobot-avatar">
<img src="qrobot.png" alt="Qrobot">
</div>
<div class="qrobot-content">
<p>{{ message }}</p>
</div>
</div>
<div class="qrobot-input">
<input type="text" v-model="input" @keyup.enter="sendMessage">
<button @click="sendMessage">发送</button>
</div>
</div>
</template>
<script>
export default {
name: 'Qrobot',
data() {
return {
message: '你好,我是小Q,有什么可以帮到你?',
input: ''
}
},
methods: {
sendMessage() {
if (this.input.trim() === '') {
return
}
this.message = '...'
axios.get('http://api.tianapi.com/robot/index?key=YOUR_API_KEY&question=' + this.input)
.then(response => {
this.message = response.data.newslist[0].reply
})
.catch(error => {
this.message = '抱歉,我无法理解你的问题。'
})
this.input = ''
}
}
}
</script>
<style scoped>
.qrobot {
width: 300px;
margin: 100px auto;
}
.qrobot-container {
display: flex;
align-items: center;
background: #efefef;
padding: 20px;
border-radius: 5px;
}
.qrobot-avatar {
width: 60px;
height: 60px;
margin-right: 20px;
}
.qrobot-avatar img {
width: 100%;
height: 100%;
border-radius: 50%;
}
.qrobot-content {
flex: 1;
}
.qrobot-content p {
margin: 0;
font-size: 16px;
}
.qrobot-input {
margin-top: 20px;
}
.qrobot-input input {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}
.qrobot-input button {
margin-left: 10px;
padding: 10px 20px;
background: #0099ff;
color: #fff;
border: none;
border-radius: 5px;
}
</style>
在App.vue文件中,引入Qrobot组件:
<template>
<div id="app">
<Qrobot />
</div>
</template>
<script>
import Qrobot from './Qrobot.vue'
export default {
name: 'App',
components: {
Qrobot
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
</style>
最后,在style.css文件中,添加一些全局样式:
body {
margin: 0;
font-family: 'Avenir', Helvetica, Arial, sans-serif;
}
现在,你可以运行npm run serve
命令,在浏览器中打开http://localhost:8080
,你将看到一个小Q机器人正在等待着你!
希望本教程对您有所帮助。如果您有任何问题,请随时与我联系。