Vue的一些API理解整理,如何一次引入多次调用

在我们做vue项目时通常会创一个config文件夹,里面一般会包含 api.js和index.js,其中api.js一般用于存放一些url地址,例如

let base = 'http://192.168.1.110:8081/hhdj/'
export default {
  login: `${base}login/login.do`,
  codeUrl: `${base}validatecode.jsp`,
  newsList: `${base}news/newsList.do`
}

或者这样写

const serverUrl = 'http://www.fooju.cn/fjw/api.php?'
export default {
  serverUrl: 'http://www.fooju.cn/',
  map: 'http://online0.map.bdimg.com/tile/?qt=tile',
  login: serverUrl + 's=Login/login', /* 登录 */
  register: serverUrl + 's=Login/register', /* 注册 */

对于index.js文件里面存放的是将数据发送给服务端的一些处理,例如

import api from './api'
import axios from 'axios'
axios.defaults.withCredentials = true
let qs = require('qs')

export const login = data => {
  console.log('login api')
  return axios.post(api.login, qs.stringify(data))
}
export const codeUrl = api.codeUrl
export const getNews = data => {
  return axios.get(api.newsList, {params: data})
}

或者

import api from './api'
import axios from 'axios'
var qs = require('qs')
axios.defaults.withCredentials = true

export const getNewsList = params => {
  return axios.get (config.getNewsList, {params: params})
}
export const saveNews = formdata => {
  return axios.post (config.saveNews, formdata)
}
function createPostParams (obj) {
  return qs.stringify(obj)
}
export const login = data => {
  return axios.post (config.login, qs.stringify(data))
} 

对于index.js文件中export输出的方法,我们可以在main.js中一次性引入,然后在vue中的文件通过this.$api.XXX()调用,例如

import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-default/index.css'
import * as api from './config'
//这里需要注意的是路径只写到相应的文件夹下面即可
import mycom from './components/index'
import store from './store/store'
Vue.prototype.$api = api
Vue.config.productionTip = false
Vue.use(ElementUI)
Vue.use(mycom)
Vue.test = function () {
  alert()
}
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store:store,
  template: '',
  components: { App }
})

在不用的vue文件中调用方法为,

<template>
  <div>
    <el-input v-model="user.username">el-input>
    <el-input v-model="user.password">el-input>
    <el-input v-model="user.checkcode">el-input>
    <img :src="codeurl" alt="">
    <el-button type="sucess" @click="loginUser">提交el-button>
   
    <router-link to="/demo/222">2222router-link>
    <router-link to="/demo/111">1111router-link>
  div>
template>

<script>
  export default{
    data () {
      return {
        user: {
          username: '',
          password: '',
          checkcode: ''
        },
        codeurl: ''
      }
    },
    methods: {
      loginUser () {
        this.$store.commit('setUser',this.user)
        this.$router.push('/demo/11')
        /*this.$api.login(this.user).then(function (res) {
          console.log(res.data)
        })*/这里是调用不同方法的地方this.$api.login()
      }
    }
  }
script>

<style scoped>

style>

http://blog.csdn.net/heliumlau/article/details/70182966

你可能感兴趣的:(web)