VueJS方法没有返回Axios的响应

时间:2018-06-17 05:33:31

标签: javascript vue.js promise vuejs2 axios

现在尝试解决这个问题,我知道这很简单,但似乎无法弄清楚问题。当我尝试返回Axios响应时,我的输出为{}。当我没有返回整个axios.post我的输出什么都没有。但当我console.log数据显示在控制台中时很好。所以我知道我正确地得到了数据。下面是我的测试代码。不知道我做错了什么,如果有人有想法,我会非常感激。

<template>
    <div>
        {{ fetch_name('my_name') }}
    </div>
</template>
<script>
import axios from 'axios'
export default {
    data() {
        return {
        }
    },
    methods: {
        fetch_name(name) {
            return axios.post('example.com/api/names', {custom: 'SELECT name FROM `names` WHERE name = "'+name+'"'}).then(response => {
                console.log(response.data[0].name)
                return response.data[0].name
            })
        }
    }
}
</script>

2 个答案:

答案 0 :(得分:2)

您案件的解决方案:

<template>
    <div>
        {{ fetch_name('my_name') && result }}
    </div>
</template>
<script>
    import axios from 'axios'
    export default {
        data() {
            return {
                result: 'Loading...',
            }
        },
        methods: {
            fetch_name(name) {
                return axios.post('example.com/api/names', {custom: 'SELECT name FROM `names` WHERE name = "'+name+'"'}).then(response => {
                    console.log(response.data[0].name)
                    this.result = response.data[0].name;
                    return response.data[0].name
                })
            }
        }
    }
</script>

但我认为更好地修改这样的逻辑:

在UI中使用控件名称的解决方案:

<template>
    <div>
        <input v-model="name">
        {{ result }}
    </div>
</template>
<script>
    import axios from 'axios'
    export default {
        data() {
            return {
                name: null,
                result: 'Wait for typing',
            }
        },
        watch: {
            name(name) {
                this.result = 'Loading...';
                axios.post('example.com/api/names', {custom: 'SELECT name FROM `names` WHERE name = "'+name+'"'})
                    .then(response => {
                        this.result = response.data[0].name;
                        return response.data[0].name
                    })
            }
        },
    }
</script>

答案 1 :(得分:0)

return response.data[0].name

在发布帖子后,fetch_name取回名称的返回值不会返回....

您需要做的是将响应放入数据中,然后绑定到您的数据,而不是方法。当对帖子的响应进入时,它将触发UI更新。

此外,从客户端发送SQL似乎非常危险。