这次我们介绍与后端api的交互,也就是使用 vue 发送请求,我们这里用到了一个别人做好的库,叫 vue-axios,先安装
npm install --save axios vue-axios
然后在我们之前用的项目中的 main.js 中引入
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
使用方法也很简单,但是由于前端与后端分离,所以要解决跨域的问题
export default {
name: 'app',
data() {
return {
todos:[
{id:0,title:'Learn vue',completed:false}
]
}
},
mounted() {
this.axios.get('http://127.0.0.1/vue/test.php').then(response => {
this.todos = response.data;
console.log(response.data)
})
},
computed: { //处理页面中展示的一些数据
todoCount(){
return this.todos.length;
}
},
components: {
Hello, Todos, TodoForm
}
}