0

Here is my script :

<html>

<script src="https://unpkg.com/vue"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.0/axios.js"></script>

<body>


    <div id="app-3">
        <span v-if="seen">{{ textFromApi }}</span>
    </div>
    <br/>


    <script type="text/javascript"> 
        var app3 = new Vue({
            el: '#app-3',
            data: {
                seen: true,
                textFromApi: "hello"
            },
            methods: {
                getData() {
                    return axios.get('https://jsonplaceholder.typicode.com/posts/1')
                },
            },
            created: function () {
                this.textFromApi = this.getData();
            }
        })
    </script>
</body>
</html>

I'm trying to modify this.textFromApi from the call of this api: https://jsonplaceholder.typicode.com/posts/1

but my this.textFromApi doesn't seems to update, any ideas why?

Here is a fiddle code: https://jsfiddle.net/bussiere/5t3v013o/

Edited from remark just below

Regards and thanks

1 Answer 1

1

created() is a lifecycle hook, it should be at the same level as data, methods, computed etc. Not a child of methods (so if you nest created() in methods() it will never get executed unless you call the method).

You also don't do anything with the axios promise, you should process it using then ().

<script src="https://unpkg.com/vue"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.0/axios.js"></script>
<body>


    <div id="app-3">
        <span v-if="seen">{{ textFromApi }}</span>
    </div>
    <br/>


    <script type="text/javascript"> 
        var app3 = new Vue({
        el: '#app-3',
        data () {
                return {
                    seen: true,
                    textFromApi: { title: 'empty'}
            }
        },
        methods: {
            getData() {
                return axios.get('https://jsonplaceholder.typicode.com/posts/1').then(response => {
                   this.textFromApi = response.data
                })
            },
        },
        created: function () {
            this.getData();
        }
    })
    </script>
</body>

</html>
Sign up to request clarification or add additional context in comments.

2 Comments

if i'am not wrong still not working : jsfiddle.net/bussiere/5t3v013o and edited but htanks
Axios needs a promise like this: jsfiddle.net/5t3v013o/1 I also updated my answer to include the promise.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.