1

I want to dispay my ip address depend on click botton in vue.

Here is my code

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"> 
</script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue- 
resource/0.1.13/vue-resource.min.js"></script>

<div id="my_view">
    <button v-on:click="greet">origin</button>
    <p>{{ message }} </p>
</div>
<script>
new Vue({
    el: '#my_view',
    data: {
       message: ''
    },


    methods: {
        greet: function (data) {
            this.$http.get('http://httpbin.org/ip', function (data) {
                // set data on vm
                this.$set('message', data.origin)

            }).error(function (data, status, request) {
                // handle error
            })
        }
    }
})
</script>

But when i click button, nothing display.

In console, print this:

vue.js:597 [Vue warn]: Cannot set reactive property on undefined, null, 
or primitive value: message

How to fix it?

Vue version: 2.5.17

2
  • this is not set in a bare function. Use an arrow function. Also, $set should take three arguments. You're leaving out the first. Commented Oct 23, 2018 at 1:45
  • @RoyJ Well, I don't know how to write code depond on your describe... Commented Oct 23, 2018 at 1:51

1 Answer 1

1

you can use this follow instead

this.$http.get('http://httpbin.org/ip', (data) => {
  // set data on vm
  this.$set('message', data.origin)      

}).error(function (data, status, request) {
  // handle error
})
Sign up to request clarification or add additional context in comments.

4 Comments

I have a try. But it seems like message variable is wrong. vue.js:597 [Vue warn]: Cannot set reactive property on undefined, null, or primitive value: message
you don't need to use $set, this.message=data.origin is the good way, $set use in array or object target
It's ok. Thanks.
To use set correctly, first argument should be a context, so code should look like: this.$set(this, 'message', data.origin). But it is correct, that $set should be used only for specific cases, when reactivy does not work as expected, e.g. dynamically created arrays of objects or multiple level nested objects, that were not declared initially in component's data.

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.