下载并安装 CodeIgniter (只负责提供接口)
![](https://img.haomeiwen.com/i7704547/18bb65a9d5c9c934.png)
这是正常CI给的初始页面,CI让我们更改welcome_message文件更换视图,具体方法在controllers/welcome中,但是我们并不需要,因为视图层会用vue,先吧控制器方法做写更改
![](https://img.haomeiwen.com/i7704547/6d56ce2f0a1a7964.png)
更改原控制器welcome
/controllers/welcome/index方法 移除加载视图代码
$result=array(
'user'=>'admin',
'pass'=>123456,
'u_id'=>753951
);
$data=array(
'code'=>200,
'msg'=>'请求成功',
'data'=>$result
);
echo json_encode($data);
重新访问CI
![](https://img.haomeiwen.com/i7704547/6d49849ddf484ca0.png)
到此CI部分告一段落 开始构建vue
安装vue-cli并初始化项目
cnpm install webpack ci_vue
![](https://img.haomeiwen.com/i7704547/cbdef31cf6b6e063.png)
初始化项目完成-安装好依赖-并成功启动
![](https://img.haomeiwen.com/i7704547/84ca2c6e7a802890.png)
通过axios请求CI中写好的接口
安装axios
cnpm install axios --save-dev
项目中引入axios 修改文件main.js
import Axios from 'axios'
//配置全局
Vue.prototype.axios=Axios
在组件中使用 修改文件components/HelloWorld.vue
注释部分为ES5写法,需要在修改data的时候提前存入this 而用es6箭头函数则不需要
html部分 在页面最下面添加
<div><button @click="getPhpData">getData</button></div>
<ul>
<li>u_name:<span>{{user_info.user}}</span></li>
<li>u_pass:<span>{{user_info.pass}}</span></li>
<li>u_id:<span>{{user_info.u_id}}</span></li>
</ul>
js部分 初始data数据,添加方法getPhpData
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome to Your Vue.js App',
user_info:{}
}
},
methods:{
getPhpData:function(){
//es5
// var this_=this
// this.axios.get('http://localhost').then(function(res){
// if(res.data.code==200){
// this_.user_info=res.data.data
// }
// }).catch(function(err){
// console.log(err)
// })
//es6
this.axios.post('http://localhost').then(res=>{
if(res.data.code==200){
this.user_info=res.data.data
}
}).catch(err=>{console.log(err)})
}
}
}
现在打开vue页面 点button请求,没有数据返回,打开控制台
![](https://img.haomeiwen.com/i7704547/653df03cdb5681a5.png)
在CI中设置跨域 welcome.php
在页头添加:指定访问,也可以设置为*或者多设置几个访问链接
header('Access-Control-Allow-Origin:http://localhost:8080');
在Vue页面中重新点击button请求
![](https://img.haomeiwen.com/i7704547/076ac26b27b06ada.png)
![](https://img.haomeiwen.com/i7704547/8866f7688bafde9d.png)
![](https://img.haomeiwen.com/i7704547/904e15823d5120c9.png)
网友评论