今天来和大家聊一下,vue项目中如何与后端php相结合。
目录结构
Home.vue
<template>
<div>
<homelist :list="list"></homelist>
</div>
</template>
<script>
import axios from 'axios'
import homelist from "./pages/HomeList"
export default {
name:"Home",
components:{
homelist
},
computed:{
list(){
return this.$store.getters.list
}
},
mounted(){
this.$store.dispatch("getInfo")
}
}
</script>
<style>
</style>
HomeList.vue
<template>
<div class="container">
<div class="list-group">
<router-link class="list-group-item" v-for="item in list" :key="item.id" :to="'/detail/'+item.id">
{{item.aram_title}}
</router-link>
</div>
</div>
</template>
<script>
export default {
name:"HomeList",
props:{
list:Array
},
data(){
return {
}
}
}
</script>
<style>
</style>
HomeDetail.vue
<template>
<div class="container">
{{content}}
</div>
</template>
<script>
import axios from 'axios'
export default {
name:"HomeDetail",
data(){
return {
content:""
}
},
// this.$route.params.id
mounted(){
var _this = this
axios.get("/api/detail.php",{
params:{
id:this.$route.params.id
}
})
.then(function(res){
var data = res.data
_this.content = data[0].aram_content
}).catch(function(res){
})
}
}
</script>
<style scoped="scoped">
</style>
配置路由,router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import home from "@/components/Home"
import homedetail from "@/components/pages/HomeDetail"
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'home',
component: home,
},
{
path:"/detail/:id",
component:homedetail
}
]
})
设置config/index.js
proxyTable: {
"/api":{
target:"http://localhost:80"
}
},
store/index.js
import Vue from 'vue'
import Vuex from "vuex"
import axios from 'axios'
Vue.use(Vuex)
const state = {
list:[]
}
const mutations = {
getInfo(state,data){
state.list = data
}
}
const actions = {
getInfo(ctx){
axios.get("/api/data.php")
.then(function(res){
var data = res.data
ctx.commit("getInfo",data)
}).catch(function(res){
console.log(res)
})
}
}
const getters = {
list(){
return state.list
}
}
export default new Vuex.Store({
state,
mutations,
actions,
getters
})