Vuecli 配合后端php

在很多情况下前端并不清楚后端与前端怎么协同工作的,下面的例子是后端用的php集成包wamp,

php文件存放在www--appi--index.php

<?php
header("Content-Type: application/json;charset=utf-8"); 
$success = true;
$data = array('a' => "this is from backend11112",'e' => "54");

// 返回json数据,或者字符串,数字。
$res = array('success' =>$success, 'data' =>$data);
echo json_encode($res);

?>  

调用后台的数据采用的axios

首先安装axios,npm install axios --save

main.js引用axios

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-default/index.css'
import router from './router'
//引用API文件
import axios from 'axios'
//import api from './api/index.js'
//将API方法绑定到全局
Vue.prototype.$ajax = axios
//引用工具文件
import utils from './utils/index.js'
//将工具方法绑定到全局
Vue.prototype.$utils=utils
Vue.use(ElementUI)
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app1',
  router,
  template: '<App/>',
  components: { App }
})

config文件夹下的index.js主要配置 

proxyTable: {
         '/api': {
          target: 'http://127.0.0.1:80',
          changeOrigin: true,
          pathRewrite: {
           '^/api': '/'
          }
         }
    },

// see http://vuejs-templates.github.io/webpack for documentation.
var path = require('path')

module.exports = {
  build: {
    env: require('./prod.env'),
    index: path.resolve(__dirname, '../dist/index.html'),
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/dist/',
    productionSourceMap: false,
    // Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],
    // Run the build command with an extra argument to
    // View the bundle analyzer report after build finishes:
    // `npm run build --report`
    // Set to `true` or `false` to always turn it on or off
    bundleAnalyzerReport: process.env.npm_config_report
  },
  dev: {
    env: require('./dev.env'),
    port: 8080,
    autoOpenBrowser: true,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
         '/api': {
          target: 'http://127.0.0.1:80',
          changeOrigin: true,
          pathRewrite: {
           '^/api': '/'
          }
         }
        // '/api/v1/**':{
        //     target:'https://cnodejs.org',//你接口的域名
        //     secure:false,
        //     changeOrigin:true,
        // }
    },
    // '/api/v1/**'也可以写成'/api'
    // CSS Sourcemaps off by default because relative paths are "buggy"
    // with this option, according to the CSS-Loader README
    // (https://github.com/webpack/css-loader#sourcemaps)
    // In our experience, they generally work as expected,
    // just be aware of this issue when enabling this option.
    cssSourceMap: false
  }
}

index.vue

<template>
  <div>
    hi everyone
    <h2>{{msg}}</h2>
  </div>
</template>
<script>
export default {
  data() {
    return {
      msg: ""
    }
  },
  created() {
    this.getData()
  },
  methods: {

    getData() {
      let _this = this;  
      _this.$ajax.get('api/appi/index.php')
        .then(function(response) {
         console.log(response)
          _this.msg = response.data.data.a
          //response.data是返回请求的json对象
        })
        .catch(function(error) {
          console.log(error);
        });

    }
  }
}

</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
ul>li {
  margin-bottom: 30px;
}

.time {
  margin-bottom: 10px;
}

</style>

特别注意路径要写成api/appi/index.php

转载于:https://my.oschina.net/u/2612473/blog/1548448

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue CLI可以通过axios等HTTP客户端库来连接后端。以下是一些步骤: 1. 安装axios库 在终端中输入以下命令来安装axios库: ``` npm install axios --save ``` 2. 创建一个API模块 在src目录下创建一个api目录,并在其中创建一个index.js文件。 在index.js文件中,可以使用axios库来定义与后端通信的API方法。例如: ```javascript import axios from 'axios' export default { // 获取用户列表 getUsers() { return axios.get('/api/users') }, // 获取单个用户 getUser(id) { return axios.get(`/api/users/${id}`) }, // 创建用户 createUser(user) { return axios.post('/api/users', user) }, // 更新用户 updateUser(id, user) { return axios.put(`/api/users/${id}`, user) }, // 删除用户 deleteUser(id) { return axios.delete(`/api/users/${id}`) } } ``` 在这个例子中,我们定义了5个方法来获取、创建、更新和删除用户。这些方法使用了axios库来发送HTTP请求到后端API。 3. 在组件中使用API 在Vue组件中,可以使用API模块来调用后端API。例如: ```javascript import api from '@/api' export default { data() { return { users: [] } }, mounted() { api.getUsers() .then(response => { this.users = response.data }) .catch(error => { console.log(error) }) } } ``` 在这个例子中,我们在组件的mounted钩子函数中调用了API模块中的getUsers方法,并将返回的用户列表保存到组件的数据中。 这就是使用Vue CLI连接后端的基本步骤。需要注意的是,在实际的项目中,可能需要对API模块进行更复杂的配置和封装,以满足具体的业务需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值