Building Your First Component

Let’s dive straight in and build our first simple Component. Like all Vue components, we have 3 sections:

  • template
  • script
  • style

Let’s start with a simple template:

and some basic styles:

Note that the style tag uses the scoped attribute, which means that these styles are scoped to this Component only.

Ok, on to the script:

This is the simplest kind of bootstrapped structure for our Vue component.

name: This enables us to register our component for use inside other components props: This is where we declare any data we would like to be provided to our component, e.g. from the parent. In our example, we’re going to pass in whether a message is sent from a User, a Bot or None and change the colour of the Text accordingly. data: For holding data in our Component state, we’re not using it in this example methods: Functions that we can call inside our component computed: Similar to methods, but designed to simplify your expressions that you may be inclined to put in your templates. Vue docs state:

computed properties are cached based on their dependencies. A computed property will only re-evaluate when some of its dependencies have changed.

So now, when I preview our Component in the Result tab and change the initial default Props value, we can see that the text colour will change accordingly.

https://guild-uploads.s3.amazonaws.com/optimized/1X/9c17fa169d2e8f9c046c044b81114562cd76776a_1_690x312.jpg

https://guild-uploads.s3.amazonaws.com/optimized/1X/1b4ed65c5914c615e0d6f8fb1912365d9d0a54dd_1_690x325.jpg

https://guild-uploads.s3.amazonaws.com/optimized/1X/44e9b827528065af0a8246e793b41032efcb0e8c_1_690x313.png

Here's the full Component code, for reference:

Questions or comments about this page?

Add a Topic