vue2.0 獲取從http接口中獲取數據,組件開發,路由配置

vue 2.0 從接口中獲取數據

<template>
  <div id="admins">
    <h1>I am a title.</h1>
    <a> written by {{ author }} </a>
    <div  v-for="admin in users">
      {{admin.name}}<br>{{admin.password}}
    </div>
  </div>
</template>

<script type="text/javascript">
import axios from 'axios'
export default {
  name: 'admins',
  data () {
    return {
      author: "there is nonthing",
      users:[]
    }
  },
  mounted(){
    this.getAdminList()
  },
  methods:{
      getAdminList(){
      var vm=this; 
      axios.get('/api/admins')
      .then(function(response){
         vm.users=response.data
      })
    }
  } 
}
</script>

<style>
</style>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37

解決axios發起http請求遇到跨域的問題 
修改 config/index.js

 proxyTable: {
        '/api': {
        target: 'http://127.0.0.1:8080',//設置你調用的接口域名和端口號 別忘了加http
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''//這裏理解成用‘/api’代替target裏面的地址,後面組件中我們掉接口時直接用api代替 比如我要調用'http://40.00.100.100:3002/user/add',直接寫‘/api/user/add’即可
        }
      }
    },
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

配置router

new Router({
  mode:'history',
  base:__dirname,
  routes: [
   {
      path: '/HelloWorld',
      name: 'HelloWorld',
      component: HelloWorld
    },
    {
      path: '/admins',
      name: 'admins',
      component: admins
    }
  ]
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

加載組件

import admins from '@/components/HelloWorld'
export default {
  name: 'App',
  data () {
    return {
      Msg: "there is nonthing",
      seen:false
    }
  },
  componets:{
    HelloWorld
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

心得:vue相當於 和可以自定義html中的標籤 和 屬性。 
在開發過程中,首先容易出現的是標點符號問題,其次是缺少引用的js,或者組件。 
感覺看視頻中的寫法和網絡上流傳的寫法有些地方差別很大,特別是調用http接口獲取數據,還是參考網上使用axios解決跨域問題,比較好,此外,官網視頻中使用的是在create裏面發請求獲取數據,但是會報錯,使用mounted不會報錯。當然使用npm進行管理的話,首先要了解一下整個項目的目錄結構。瞭解完之後再進行開發,纔會避免摸不着頭腦的情況

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章