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

相关文章
相关标签/搜索