天天看點

webpack4.0.1_vue腳手架的項目與json-server結合,vue開發前端時用json-server模拟資料,fetch的請求代碼

寫在前面的話:

      在完成現代web開發時,一個公司中,前後端同時進行開發,前端開發頁面邏輯,後端處理業務邏輯。在後端還沒有開發好,即沒有提供資料是,則提前寫好前後端的資料接口,前端人員利用json-server模拟出資料,前端利用fetch(或ajax)從json-server上請求到資料,進行動态資料的展示。等到後端人員把業務邏輯寫好後。再把請求位址換成後端的即可。

正式開始:

        前端利用vue腳手架,或者自行搭建好vue項目後,把json-server也結合到項目中,這樣前端就可以開始自己的頁面邏輯開發了。

        下面就說一下,如何把json-server融合到vue腳手架項目中,如果不會vue腳手架搭建項目(搭建很簡單)的話,請先看一下這篇文章:vue腳手架(vue-cli)如何搭建項目。

        1、前提已經用vue搭建好了項目

        2、建立模拟資料:在build目錄下建立檔案:db.json。在檔案裡寫上如下代碼:        

[html]  view plain  copy

  1. {  
  2.     "books":[  
  3.         {"id":"878911","name":"三國","author":"羅貫中"},  
  4.         {"id":"878912","name":"水浒","author":"吳承恩"}  
  5.     ],  
  6.     "readers":[  
  7.         {"id":"007","name":"張三瘋","age":35},  
  8.         {"id":"008","name":"張四瘋","age":32}    
  9.     ]  
  10. }  

            以上代碼表示你有兩類資料,分别是書籍(books)和讀者(readers),相當于資料庫中表,mongod中叫集合。   

             你可以根據你的項目實際情況,寫出你的資料    

       3、搭建json-server伺服器

              1)、安裝json-server子產品,npm i json-server  -D

              2)、在build目錄下建立jserver.js(這是nodejs做的簡易伺服器)。寫上如下代碼:                

[html]  view plain  copy

  1. const path = require("path");  
  2. //引入:json-server子產品  
  3. const jsonserver = require("json-server");  
  4. //用jsonserver建立服務對象  
  5. const jserver = jsonserver.create();  
  6. //建立路由  
  7. const jrouter = jsonserver.router(path.join(__dirname,"db.json"));  
  8. //定義中間件  
  9. const middlewares = jsonserver.defaults();  
  10. //nodejs的思路,每次請求伺服器是,都會執行middlewares中間件  
  11. jserver.use(middlewares);  
  12. //路由,會根據請求,找對應的資料,如:books或者readers  
  13. jserver.use(jrouter);  
  14. //啟動伺服器  
  15. jserver.listen(8081,()=>{  
  16.     console.log("json-server running in 8081");  
  17. });  

              3)、如果想測試json-server伺服器配置是否成功,按照如下步驟:

                      (1)、在build目錄下執行指令:node jserver.js,如果出現了提示json-server running in 8081,說明啟動成

                      (2)、在浏覽器中輸入:http://localhost:8081/books。如果在浏覽器裡看到了如下内容,說明成功了。

[
  {
    "id": "878911",
    "name": "三國",
    "author": "羅貫中"
  },
  {
    "id": "878912",
    "name": "水浒",
    "author": "吳承恩"
  }
]      

                (3)、在浏覽器中輸入:http://localhost:8081/books?id=878912,你會發現可以取到id為878912的書籍資訊:

[
  {
    "id": "878912",
    "name": "水浒",
    "author": "吳承恩"
  }
]
           

當然你也可以看看readers的資料(在浏覽器輸入:http://localhost:8081/readers)

當然你也可以看看readers的資料(在浏覽器輸入:http://localhost:8081/readers)

          4)、配置服務代理

                 此步驟的意思是以後,通路vue腳手架中啟動的服務時,會引入到json-server服務下,什麼意思呢,下面詳細解釋,先寫代碼。

                 打開項目目錄下的config下的index.js檔案。找到 dev:屬性,該屬性一般預設會有 proxyTable: {}。如果沒有自己寫上就行,    在花括号裡寫如下代碼:

[html]  view plain  copy

  1. module.exports = {  
  2.   dev: {  
  3.     // Paths  
  4.     assetsSubDirectory: 'static',  
  5.     assetsPublicPath: '/',  
  6.     <span style="color:#ff0000;">proxyTable: {  
  7.         '/api':{      
  8.           target: 'http://localhost:8081',  
  9.           pathRewrite: {'^/api' : ''}, //api 做為辨別,到最後是要被替換掉的。  
  10.           changeOrigin: true  
  11.           }  
  12.     }</span>,………………………………  

     此代碼的意思是:如何通路的是/api路徑,那麼就轉到http://localhost:8081下。

          5)、啟動測試:

                (1)、啟動json-server伺服器(即資料來源的伺服器):

                           在build目錄下執行指令:node jserver.js,如果出現了提示json-server running in 8081,說明成功

                 (2)、啟動vue腳手架項目伺服器:

                          在vue腳手架項目下執行指令:npm run dev,如果出現了提示“Your application is running here: http://localhost:706”,說明成功。

                 (3)、在浏覽器中測試:

                             在位址欄中輸入:http://localhost:706/api/books,在浏覽器中看到了:

[html]  view plain  copy

  1. [  
  2.   {  
  3.     "id": "878911",  
  4.     "name": "三國",  
  5.     "author": "羅貫中"  
  6.   },  
  7.   {  
  8.     "id": "878912",  
  9.     "name": "水浒",  
  10.     "author": "吳承恩"  
  11.   }  
  12. ]  

                            說明一切ok。

             6)、使用fetch,請求位址http://localhost:706/api/books,就可以拿到書籍資訊了。

<template>
  <div class="goodslistcss">
    <ul>
		<li v-for="item in goodslist">
		<p @click="goGoodsdetail(item.goodsid)">商品編号:{{item.goodsid}}</p>
			<p class="title">商品名稱:{{item.goodsname}}</p>
			<p>商品價格:{{item.goodsprice}}</p>
		</li>
	</ul>
  </div>
</template>

<script>

import common from "../assets/common.css"

export default {
  name: 'goodslist',
	methods:{
		goGoodsdetail:function(goodsid){
			//儲存商品編号
			this.$store.state.id=goodsid;
		    //跳轉
			 this.$router.push({ path: '/goodsdetail/:id',name:"goodsdetail",params: { goodsid:goodsid}});
		},
		getGoodsList:function(){
			fetch('api/goodslists',{
				method:"GET",
				headers: new Headers({
				  'Accept': 'application/json' // 通過頭指定,擷取的資料類型是JSON
				})
		   }) // 傳回一個Promise對象,
		  .then((res)=>{
			 return res.json() // res.json()是一個Promise對象
		  })
		  .then((res)=>{
		    console.log(res) // res是最終的結果
		    this.goodslist = res;
		  })
		}
	},
	mounted:function(){
		this.getGoodsList();
	},
  data () {
    return {
      goodslist: []
    }
  }
}
</script>

<style scoped>
.goodslistcss{
	width:1000px;
	height:400px;
	background-color:gray;
}
</style>
           

加油,加油,加油!