在Vue中使用axios基础方式

简单的为大家介绍一下如何在vue中使用axios
我们需要先了解json-server,我们要搭建服务
可以先看一下本人的这篇:json-server的基础使用

基础使用

上代码:

DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>title>
head>

<body>
    <div id="root">
        <button @click="search">点击发送GET请求button>
    div>
body>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.5.0/axios.js">script>
<script src="../JS/vue.js">script>
<script>
    const vm = new Vue({
        el: "#root",
        methods: {
            search() {
                // 第一种方式
                // axios({
                // 请求方式
                //     method: "GET",
                // 请求的url
                //     url: "http://localhost:3000/posts"
                // }).then(res => {
                //     console.log(res);
                // })

                // 第二种方式 常用
                // 比较方便 第一个直接写url
                axios.get("http://localhost:3000/posts").then(res => {
                    console.log(res);
                })
            }
        },
    })
script>

html>

在Vue中使用axios基础方式_第1张图片

渲染页面的方式

DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>title>
head>

<body>
    <div id="root">
        <button @click="search">点击发送GET请求button>
        <ul>
            <li v-for="item in list" :key="item.id">
                {{item.id}}--{{item.title}}--{{item.author}}
            li>
        ul>
    div>
body>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.5.0/axios.js">script>
<script src="../JS/vue.js">script>
<script>
    const vm = new Vue({
        el: "#root",
        data: {
            list: []
        },
        methods: {
            search() {
                // 第一种方式
                // axios({
                // 请求方式
                //     method: "GET",
                // 请求的url
                //     url: "http://localhost:3000/posts"
                // }).then(res => {
                //     console.log(res);
                // })

                // 第二种方式 常用
                // 比较方便 第一个直接写url
                axios.get("http://localhost:3000/posts").then(res => {
                    // console.log(res);
                    this.list = res.data
                })
            }
        },
    })
script>

html>

点击GET按钮后
在Vue中使用axios基础方式_第2张图片

感谢大家的阅读,如有不对的地方,可以向我提出,感谢大家!

你可能感兴趣的:(vue.js,前端,javascript)