網上參考了很多例子,都沒有關於vue+php實現前後端的例子,後來自己總結了一個,希望大家批評指正。
vue實現動態數據的方式主要有vue-resource和axios,但是從Vue2.0開始,已經不對vue-resource進行更新,因此,本文主要利用axios進行操作。
1、安裝axios
npm install axios --save
2、在Vue-cli的components中編寫組件
<template>
<div 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>
</div>
</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>
本文創建的數據表信息主要由id、user、name、intro幾個
可以根據自己的需求,自己創建。具體的創建方式,網上很多,此處不再詳細描述。創建的數據如下:
4、需要請求的php
<?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
?>
則最終在液麪上輸出的結果也爲上面數據表那張圖所示。