1

I'm using the example from https://v2.vuejs.org/v2/guide/events.html#Method-Event-Handlers

I want to hide a message in #content when the button is clicked, but I encountered weird problem: button element disappears when v-on:click contains anything. When I remove "switch" from it, button appears on page.

Also, my second question: Is this the proper way of showing/hiding things using Vuejs?

My code:

<div id="navigation">
    <button v-on:click="switch">Switch</button>
</div>

<div id="content">
    <p v-if="show">{{ message}}</p>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script>
    var content = new Vue({
        el: '#content',
        data: {
            message: 'Hello Vue!',
            show: true
        }
    });

    var navigation = new Vue({
        el: '#navigation',
        data: {
        },
        methods: {
            switch: function() {
                content.show = !content.show;
            }
        }
    });
</script>

1 Answer 1

3

switch is a reserved Javascript keyword, using another name such as toggle for the method will solve the problem.

var content = new Vue({
  el: '#content',
  data: {
    message: 'Hello Vue!',
    show: true
  }
});

var navigation = new Vue({
  el: '#navigation',
  data: {},
  methods: {
    toggle: function() {
      content.show = !content.show;
    }
  }
});
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="navigation">
  <button v-on:click="toggle">Switch</button>
</div>

<div id="content">
  <p v-if="show">{{ message}}</p>
</div>

As a side note, I strongly discourage the approach in this example. Vue instances should be isolated. Creating components is recommended and communication between them can happen via an event bus or vuex.

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

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.