Search code examples
javascripthtmlvue.js

Vue v-show not rendering when value is changed


When I click the button, I want to show the HTML Element. The click method is changing the value of "showCreateSection", but the HTML is not showing.

I already tried different versions with and without "this" (this.showCreateSection).

Do I have to bind the variable somehow?

var CreateSectionContainer = new Vue({
    el: '#create-section-container',
    data:  {      
            showCreateSection: false
    },
    methods: {
        showCreateSectionInput: function (event) {
            console.log("showCreateSectionInput");
            console.log(this);
            this.showCreateSection = true;
        }
    }
});
<div id="create-section-container">
    <div id="task-editor" class="container tab-pane active">
        <div class="container">
            <div class="row">
                <div id="new-section-container" v-show="this.showCreateSection" class="col-md-8">
                    <h6>Section Name</h6>
                    <input type="text" id="sectionName" class="w-100 form-control" name="Name" placeholder="Name">

                </div>

                <div class="row">
                    <button type="button" v-on:click="showCreateSectionInput" class="btn btn-success"><i class="fas fa-plus-circle"></i> Add new section</button>
                    <br />
                    <hr>
                </div>
            </div>
        </div>
        <br />
        <div class="row">
            <div class="nav__list w-100" id="assignment-section-container1">
                <section-item v-for="item in sectionList" v-bind:section="item" v-bind:key="item.id">
                </section-item>
            </div>
        </div>
    </div>
</div>


Solution

  • You should use computed for that:

    var CreateSectionContainer = new Vue({
        el: '#create-section-container',
        data: function() {
            return {
                showCreateSection: false
            }      
        },
        methods: {
            showCreateSectionInput: function (event) {
                console.log("showCreateSectionInput");
                console.log(this);
                this.showCreateSection = true;
            },
            computed: {
                showSection() {
                    return this.showCreateSection;
                }
            }
        }
    });
    

    and in your html file:

    <div id="new-section-container" v-show="showSection" class="col-md-8">
      <h6>Section Name</h6>
      <input type="text" id="sectionName" class="w-100 form-control" name="Name" placeholder="Name">
    </div>