您好,登錄后才能下訂單哦!
vue 2.0 從接口中獲取數(shù)據(jù)
<template> <div id="admins"> <h2>I am a title.</h2> <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>
解決axios發(fā)起http請(qǐng)求遇到跨域的問(wèn)題
修改 config/index.js
proxyTable: { '/api': { target: 'http://127.0.0.1:8080',//設(shè)置你調(diào)用的接口域名和端口號(hào) 別忘了加http changeOrigin: true, pathRewrite: { '^/api': ''//這里理解成用‘/api'代替target里面的地址,后面組件中我們掉接口時(shí)直接用api代替 比如我要調(diào)用'http://40.00.100.100:3002/user/add',直接寫‘/api/user/add'即可 } } },
配置router
new Router({ mode:'history', base:__dirname, routes: [ { path: '/HelloWorld', name: 'HelloWorld', component: HelloWorld }, { path: '/admins', name: 'admins', component: admins } ] })
加載組件
import admins from '@/components/HelloWorld' export default { name: 'App', data () { return { Msg: "there is nonthing", seen:false } }, componets:{ HelloWorld } }
心得:vue相當(dāng)于 和可以自定義html中的標(biāo)簽 和 屬性。
在開(kāi)發(fā)過(guò)程中,首先容易出現(xiàn)的是標(biāo)點(diǎn)符號(hào)問(wèn)題,其次是缺少引用的js,或者組件。
感覺(jué)看視頻中的寫法和網(wǎng)絡(luò)上流傳的寫法有些地方差別很大,特別是調(diào)用http接口獲取數(shù)據(jù),還是參考網(wǎng)上使用axios解決跨域問(wèn)題,比較好,此外,官網(wǎng)視頻中使用的是在create里面發(fā)請(qǐng)求獲取數(shù)據(jù),但是會(huì)報(bào)錯(cuò),使用mounted不會(huì)報(bào)錯(cuò)。當(dāng)然使用npm進(jìn)行管理的話,首先要了解一下整個(gè)項(xiàng)目的目錄結(jié)構(gòu)。了解完之后再進(jìn)行開(kāi)發(fā),才會(huì)避免摸不著頭腦的情況
以上這篇vue2.0 獲取從http接口中獲取數(shù)據(jù),組件開(kāi)發(fā),路由配置方式就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。