简体   繁体   中英

modifying data variable in vue.js using axios

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM