Vue入門基礎(Axios請求)

axios.htmljavascript

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

<head>
    <meta charset="UTF-8">
    <!--引用cnd 的axios-->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <title>Insert title here</title>
</head>

<body>
    <h1>Axios請求</h1>
    <div id="app-vue-axios">

        <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="axios.js"></script>

</html>

axios.jshtml

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

頁面效果vue

相關文章
相關標籤/搜索