尝试在 Vue 组件中添加创建的方法时出错

Error when trying to add created method in Vue 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>

当我把上面的脚本代码改成下面的时候。我收到错误..

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

</script>

错误详情

意外令牌,预期;

只有在添加创建的方法时才会出现问题,我是否遗漏了什么?

您的 created(){} 方法应该封装在您的 export default {} 块中。

换句话说,将您的代码更改为:

export default {

  props: ["messages"],

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

},

created 生命周期方法在 Vue 组件本身的主体内,而不是在外部。我的意思是:

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

Vue.js Lifecycle