首页 > 解决方案 > Vue 3-mounted() 没有被组件调用?

问题描述

我有一个非常简单的 Vue 3 组件,它看起来与文档中的一些示例相同。代码如下:

// Typewriter.vue

<template>
  <div id="wrapper">
    <p>{{ text }}</p>
  </div>
</template>

<script>
export default {
  name: "typewriter",
  props: {
    phrase: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      text: "",
    };
  },
  mounted() {
    console.log('Hello World!');
  }
};
</script>

<style scoped></style>

然后我通过以下方式在另一个组件中渲染它:

<template>
    <p>Blah</p>
    <typewriter phrase="some text" />
</template>

<script>
import Typewriter from "@/components/Typewriter.vue";

export default {
  name: "bio",
  components: {
    Typewriter
  }
};
</script>

<style scoped></style>

但是,mounted()似乎没有得到调用?如果我将其更改为,setup()则方法内部的任何内容都会被调用,但这当然不适用于我的情况,因为我需要访问this组件。

我错过了一些明显的东西吗?抱歉,Vue 和学习新手。

标签: javascriptvue.jsvuejs3

解决方案


事实证明,问题出在我遵循的教程中,明确地在 Webpack 构建中(我正在使用带有 webpacker 的 Rails 应用程序),设置以下内容:

...
environment.plugins.prepend(
  "Define",
  new DefinePlugin({
    __VUE_OPTIONS_API__: false, // This is the problem
    __VUE_PROD_DEVTOOLS__: false,
  })
);

...

这当然会关闭选项 API 并强制您使用组合 API(我不是)。


推荐阅读