html靜態頁面通過vue實現資料動態化
阿新 • • 發佈:2019-02-02
1.引入vue,引入jQuery(因為等下用Ajax請求資料用到jQuery)
如:
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
2.初始化並繫結vue
首先在自己的網頁body內新增一個div包括所有內容,並給這個div設定id
如:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div id="app"> //你的html程式碼 </div> </body> </html>
3.建立vue並掛載到頁面(如果在單獨建立js檔案來寫,則需在htmll中引入這個js檔案)
建立如下:
window.onload = function() { new Vue({ el: "#app",//將vue掛載到html中你建立的那個帶id="app"上 data: { aboutData: [], //建一個空陣列,用來儲存呼叫介面獲取的資料 }, created: function() { this.getRoute(); }, mounted() { }, methods: { getRoute: function() { var that = this; $.ajax({ type: "GET", url: "填寫你的資料介面地址", dataType: "json", success: function(response) {
aboutData = response;
//寫在獲取資料成功後你想進行的操作
},
error: function() {
alert("請求失敗");
}
});
}
});
};
4.可以在html程式碼中呼叫vue相關語法來寫進動態資料了