Vue项目编写
在views下编写一个User.vue显示数据
<template>
<div>
<table>
<tr>
<td>员工编号</td>
<td>员工名称</td>
<td>员工性别</td>
</tr>
<!--表内容,循环遍历users当中的内容并展示-->
<tr v-for="item in users">
<td>{{item.id}}</td>
<td>{{item.username}}</td>
<td>{{item.usersex}}</td>
</tr>
</table>
</div>
</template>
新增一个路由到User.vue
{
path:'/user',
name:'User',
component:()=>import('../views/User.vue')
}
编写User.vue的script模块
利用axios接收数据
<template>
<div>
<table>
<tr>
<td>员工编号</td>
<td>员工名称</td>
<td>员工性别</td>
</tr>
<tr v-for="item in users" v-bind:key='item'>
<td>{{item.id}}</td>
<td>{{item.username}}</td>
<td>{{item.usersex}}</td>
</tr>
</table>
</div>
</template>
<script>
export default {
name: "User",
data(){
return{
users:[]
}
},
created(){
const _this = this
axios.get('http://localhost:8181/user/findAll').then(function(resp){
console.log(resp)
_this.users = resp.data
})
}
}
</script>
发现请求不到
涉及到跨域的问题
需要在springboot项目中添加CrosConfig类
package com.xf.demo;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CrosConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}
这里还是获取不到
原因是:配置类,但是没有任何数据经过这个类进行过滤
这里选择vue代理
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api':{
target:'http://localhost:8181/',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
},
axios中使用
<script>
export default {
name: "User",
created(){
const _this = this
axios.get('/api/user/findAll').then(function(resp){
console.log(resp)
_this.users = resp.data
})
}
}
</script>