Vue入門基礎(Fetch請求)

fetch.htmljavascript

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <title>Insert title here</title>
</head>

<body>
    <h1>Fetch請求</h1>
    <div id="app-vue-fetch">

        <form @submit.prevent="onSubmit">
            <input type="text" v-model="todo.title">
            <input type="checkbox" v-model="todo.completed">
            <input type="submit" value="提交">
        </form>

        <!--get 請求-->
        <ul>
            <li v-for="todo in todos">
                <h1>{{todo.title}}</h1>
                <p v-if="todo.completed">{{todo.completed}}</p>
            </li>
        </ul>
    </div>
</body>
<script src="fetch.js"></script>

</html>

fetch.jshtml

const one=new Vue({
    el:"#app-vue-fetch",
    data(){
        return{
           todos:[],
           todo:{
               title:"",
               completed:false
           }
        }
    },
    // mounted 是一個工做函數  打開頁面前會自動執行
    mounted(){
        //fetch api 請求接口 
        //get請求 請求成功後 從then中獲取數據賦值給res
        fetch("http://jsonplaceholder.typicode.com/todos")
        .then(res=> {
            //console.log(res);
            //console.log(res.json());
            return res.json()
        }).then(todos=>{
           // console.log(todos);
           this.todos=todos;
        })
    },
    methods:{
        onSubmit(){
             //POST 請求
            fetch("http://jsonplaceholder.typicode.com/todos",{
                method:"POST",
                body:JSON.stringify(this.todo),//對象轉json
                headers:{
                    'content-type': 'application/json'
                }
            }).then(res=>{
                return res.json();
            }).then(todo=>{
                //console.log(todo);
                this.todos.unshift(todo);//對象加入到數組裏
            });
        }
    }
});

頁面效果vue

相關文章
相關標籤/搜索