2

I couldn't manage to make it work. v-on:click event is not invoking the method on Vue instance. Here is the codes:

<div id="app">
    <button class="btn btn-success" v-on:click="postEventData">
        <i class="icon wb-share"></i> Publish
    </button>
</div>

Vue instance:

var vm = new Vue({
    el: '#app',
    data: {
        someData: 'fooBar'
    },
    methods: {
        postEventData: function () {
            axios.post('/foobar', vm._data);
        }
    }
});

Any help would be appreciated!

3
  • 1
    Your v-on:click is getting called just fine. Look at this fiddle for example fiddle.jshell.net/v1qpt8d8/1 Commented Sep 25, 2017 at 15:10
  • You need to reference this in your postEventData method, not vm Commented Sep 25, 2017 at 15:11
  • Thanks but even I copy paste the jsfiddle, it is not working. Commented Sep 25, 2017 at 15:33

3 Answers 3

1

Change this axios.post('/foobar', vm._data);

to this: axios.post('/foobar', this.data);

Sign up to request clarification or add additional context in comments.

1 Comment

I tried regular onclick="vm.postEventData()" and it is working fine. However, when I changed vm._data to this.data it is not working too. I couldn't understand why.
1

I'm not seeing anything broken with your code.

That said, it would be better practice to use this to reference the Vue instance instead of vm. But, you would still need to reference the _data property of your Vue instance to get the data object (this.data is going to be undefined).

However, while you can reference your data object via this._data, it's a code smell. Your Vue instance's data properties are meant to be accessed individually directly off of this. Accessing the whole object breaks that paradigm.

If you are trying to submit { someData: 'fooBar' } in your post request, make a data property for that (say postData) and reference it via this.postData:

 var vm = new Vue({
    el: '#app',
    data: {
        postData: { someData: 'fooBar' }
    },
    methods: {
        postEventData: function () {
            axios.post('/foobar', this.postData);
        }
    }
});

Your template with v-on:click="postEventData" is fine.

1 Comment

Thanks for detailed information! I will try your suggestions on my code and share the output in the comments later.
0

Old question but this is what worked for me if someone else is stuck

button click event was actually trying to submit form since it was contained in a form element. So in order to make it call the method I had to do @click.prevent="myMethod()"

.prevent is the key. It acted as event.preventDefault()

Comments

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.