[Vuejs]-Onclick function in vue does not render my custom component

3πŸ‘

βœ…

<template>
    <div class="page">
        <div class="content">
            <sample-button @click="showBanner()">
                Show banner
            </sample-button>
            <div id="banner" v-if="visible">
                <div class="banner-page">
                    <sample-component>
                        <p> hello </p>
                    </sample-component>
                </div>
            </div>
        </div>
    </div>
</template>

<script lang="ts">
import Vue from 'vue';

export default Vue.extend({
    data() {
        return {
            visible: false
        }
    },
    methods: {
        showBanner() {
            this.visible = true        
        },
    },
});
</script>

You just can render it by changing a data property which passed into v-if directive

πŸ‘€Mik

0πŸ‘

Please note that you shouldn’t be returning the template from the method and also you cannot assign an id to a <template> tag since they don’t actually get rendered. So you basically need to change your template to below:

<template>
  <div class="page">
    <div class="content">
      <!-- note that your banner component has shifted here -->
      <div v-if="isBannerVisible" id="banner">
        <div class="banner-page">
          <sample-component>
            <p>hello</p>
          </sample-component>
        </div>
      </div>

      <sample-button @click="isBannerVisible = true">
        Show banner
      </sample-button>
    </div>
  </div>
</template>

and your script as well to:

<script lang="ts">
import Vue from "vue";

// since your using Typescript it is better to use the class syntax
export default class MyComponent extends Vue {
  private isBannerVisible: boolean = false
};
</script>
πŸ‘€usafder

Leave a comment