本篇文章给大家分享的内容是联合vue+axios+php+mysql 更新前端界面数据动态,有着一定的参考价值,有需要的朋友可以参考一下
vue实现动态数据的方式主要有vue-resource和axios,但是从vue2.0开始,已经不对vue-resource进行更新,因此,本文主要利用axios进行操作。
1、安装axios
npm install axios --save
2、在vue-cli的components中编写组件
<span style="font-size:14px;"><template>
<p class="count">
<table cellspacing="0" border="1px">
<tr>
<th>id</th>
<th>name</th>
<th>age</th>
<th>intro</th>
</tr>
<tr v-for="user in users">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td>{{user.age}}</td>
<td>{{user.intro}}</td>
</tr>
</table>
</p>
</template>
<script>
import vuex from "vuex";
import axios from "axios";
export default{
name:'count',
data(){
return{
users: []//预先创建一个数组,用于存放请求得到的数据
}
},
created(){ //此处用created相当于对前端页面数据进行初始化
axios.get("http://xxxx/axios.php").then(res=>{ //这里是es6的写法,get请求的地址,是小编自己在网站上存放的php文件,后面将介绍其编写,也可以自己定义
this.users=res.data;//获取数据
console.log('success');
console.log(this.users);
})
}
}
</script>
<style scoped>
table{
width:600px;
height:300px;
margin:100px
}
</style></span>
3、数据库的创建
本文创建的数据表信息主要由id、user、name、intro几个
可以根据自己的需求,自己创建。具体的创建方式,网上很多,此处不再详细描述。创建的数据如下:
4、需要请求的php
<span style="font-size:14px;"><?php
header("access-control-allow-origin: *");//这个必写,否则报错
$mysqli=new mysqli('localhost','root','passwd','table');//根据自己的数据库填写
$sql="select * from users";
$res=$mysqli->query($sql);
$arr=array();
while ($row=$res->fetch_assoc()) {
$arr[]=$row;
}
$res->free();
//关闭连接
$mysqli->close();
echo(json_encode($arr));//这里用echo而不是return
?></span>
则最终在液面上输出的结果也为上面数据表那张图所示。
以上就是联合vue+axios+php+mysql 更新前端界面数据动态的详细内容。