您的位置:首页 > Web前端 > Vue.js

创新实训博客(14)——Vue前端与后端的接口交互

2020-07-14 06:21 381 查看

以获取博文内容的数据为例子,来演示前后端数据交互:

用到的模块

主要是axios、qs

封装request

[code]import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// 设置请求的地址
const service = axios.create({
baseURL: '/api',
timeout: 5000
})

// 构造请求
service.interceptors.request.use(
config => {
// 传递token,除了登录的时候没有token以外都要传
if (store.getters.token) {
config.headers['Authorization'] = getToken()
}
return config
},
error => {
// 错误
return Promise.reject(error)
}
)

// 发完请求以后的响应结果
service.interceptors.response.use(

response => {
// 后期需要返回的数据,先放着
const res = response.data
// 我的要求:200代表成功
if (res.code !== 200) {
// 设置错误信息
var out_msg = (res.code + ' - ' + res.msg) || (res.code + ' - ' + '错误!')
Message({
message: out_msg,
showClose: true,
type: 'error',
duration: 5 * 1000
})
// 是否需要重新设置token
if (res.code === 50000) {
// 跳转到resetToken
store.dispatch('user/resetToken').then(() => {
location.reload()
})
}
return Promise.reject(new Error(out_msg))
} else {
Message({
message: res.msg || '成功!',
showClose: true,
type: 'success',
duration: 5 * 1000
})
return res
}
},
error => {
Message({
message: error.message,
showClose: true,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)

export default service

api管理

按照模块的分类,同一种类型的api放在同一个js文件下。

不同的api类型放在不同的文件中,所有的vue文件都是import这些模块后调用。

向后端发请求

[code]// 获取最近的文章列表
export function getRecentArticles(page, size) {
return request({
url: '/article/list',
method: 'get',
params: { page: page, size: size }
})
}

js处理返回的数据

比如我需要进行html格式的处理,还有获取相似文章列表并且存储起来。

[code]created() {
var that = this
getArticle(that.id).then(response => {
const { data } = response
that.blog = data
that.blog.content = '<html><head><style> img{ max-width: 100%; width:auto; height: auto; }</style></head><body>' + that.blog.content + '</body></html>'
readArticle(that.id).then(response2 => {
getSimilarityArticle(that.id).then(response3 => {
const { data } = response3
that.similarList = data
})
})
})
}

在html中显示得到的数据

对于列表项,使用v-for进行显示。

[code]      <div v-for="item in similarList" :key="item.id">
<blog-brief-item :id="item.id" :title="item.title" :author="item.author" :date="item.updateTime" />
</div>

其他在前端完成的操作

以tag的分类展示为例子,在存储的时候是以#作为分隔符进行分割。

那么我传到前端以后的数据,应该使用一个split函数来进行处理。

[code]    splitDescription(data) {
return data.split('#')
}

在vue中也需要进行相应的操作

[code]      <el-table-column align="center" label="标签描述">
<template v-if="splitDescription(scope.row.description)[0]!=='\n'" slot-scope="scope">
<span v-for="item in splitDescription(scope.row.description)" :key="item">
<el-tag type="info" effect="plain" style="margin: 4px">{{ item }}</el-tag>
</span>
</template>
</el-table-column>

最终完成的显示效果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐