How to render component conditionally in Vuejs


We have seen some of the basic operations in vuejs . Now move on to advanced area. In the following example we will learn how to conditionally render a component.

Script

<script>
import Tweet from "./Tweet.vue";
export default {
  components: { Tweet },
  name: "UserProfile",
  created() {},
  data() {
    return {
      
      followers: 0,
      user: {
        tweets: [
          { id: 907, content: "new features in vue3" },
          { id: 910, content: "new features in vue2" },
        ],
        id: 90,
        uname: "codehat",
        fullName: "manoj nair",
        isAdmin: true,
      }, 
    };
  },
  props: {},
  methods: {
    
  },
  watch: {},
  computed: {
    getTweetCharacterCount() {
      return this.newTweetContent.length;
    },
    getTweetQuota() {
      return this.tweetMaxLength - this.newTweetContent.length;
    },    
  },
};
</script>


We had a special admin badge with special style attached to it and also have a property (isAdmin) which is declared in the data section as follows

Template and Style

    <template>
.........
 <div class="user-profile__admin-badge" 
v-if="user.isAdmin">Admin</div>
</template>

<style scoped>

.user-profile__admin-badge {
  background: rebeccapurple;
  color: white;
  border-radius: 5px;
  margin-right: auto;
  padding: 0 10px;
  font-weight: bold;
}
</style>

The badge meant to be visible only if the isAdmin property of data() is set to true. This can be accomplished using the v-if directive to evaluate the value of the property inside the component.

The following vue post posts may help you

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.