Home » vue » Error when trying to add created method in Vue component

Error when trying to add created method in Vue component

Posted by: admin November 26, 2021 Leave a comment

Questions:

Component

<template lang="html">
    <div class="chat-log">
        <chat-message v-for="message in messages" :message="message"></chat-message>
    </div>
</template>

<script>
    export default {
        props: ["messages"]
    }

</script>

<style lang="css">
    .chat-log .chat-message:nth-child(even) {
        background-color: #ccc;
    }
    .chat-log {
        overflow-y: auto;
        max-height: 400px;
    }

</style>

When I change the above script code to below. I get errors..

<script>
    export default {
        props: ["messages"]
    },
    created() {
        $(".chat-log").scrollTop($(".chat-log").prop('scrollHeight'));
    }

</script>

Error Details

Unexpected token, expected ;

Issue comes only when adding the created method, Am I missing anything?

Answers:

The created lifecyle method goes within the body of the Vue component itself, not outside. I mean:

export default {
    props: ["messages"],
    created() {
        $(".chat-log").scrollTop($(".chat-log").prop('scrollHeight'));
    }
 }

Vue.js Lifecycle

###

Your created(){} method should be encapsulated within your export default {} block.

In other words, change your code this:

export default {

  props: ["messages"],

  created() {
   $(".chat-log").scrollTop($(".chat-log").prop('scrollHeight'));
  }

},