0

I'm new to Vue and i want to render a component after a user clicks on a button. Maybe I'm doing it incorrectly?

The <sample-component> is just a banner that's meant to appear at the top of the page

Sample Code

<template>
    <div class="page">
        <div class="content">
            <sample-button @click="showBanner">
                Show banner
            </simplex-button>
        </div>
    </div>
</template>

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

export default Vue.extend({
    methods: {
        showBanner() {
            return `
            <template id="banner">
                <div class="banner-page">
                    <sample-component>
                        <p> hello </p>
                    </sample-component>
                </div>
            </template>`;          
        },
    },
});
</script>

2 Answers 2

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

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

Comments

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>

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.