1. 程式人生 > 實用技巧 >17.vue+axios搭配使用

17.vue+axios搭配使用

<body>
    <div id="mask">
        <button @click="getJoke">獲取笑話</button>
        <p> {{ joke }} </p>
    </div>
    <script src="http://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
    <script>
        var
mask = new Vue({ el: "#mask", data: { joke: "好笑的笑話" }, methods: { getJoke: function() { var that = this; // 因為在then方法函式裡面的 this不是指向 vue了 所以給它設個全域性變數 axios.get("https://autumnfish.cn/api/joke/list?num=1") .then(
function(response) { // 把網路請求庫裡面的笑話渲染到 定義的joke裡面 因為是一個數組 所以把它轉為字串 var arr = response.data.jokes; console.log(arr.toString()); that.joke = arr.toString(); }, function
(error) { console.log(error); }) } } }) </script> </body>