【问题标题】:Vue 3 prop not being passedVue 3 道具未通过
【发布时间】:2021-08-05 22:50:33
【问题描述】:

我正在尝试将一个简单的道具传递给 Vue 3.0.11 中的另一个组件,但我似乎无法让它工作。这是我的 App 组件:

<template>
  <Loading :message="Importing"></Loading>
</template>

<script>
import Loading from "./components/Loading.vue";
export default {
  name: "App",
  components: { Loading },
};
</script>

<style>
</style>

还有我的Loading 组件:

<template>
  <div>{{ loadingText }}...</div>
</template>

<script>
export default {
  name: "Loading",
  props: ["message"],
  data() {
    return {
      loadingText: this.message || "Loading",
    };
  },
};
</script>

<style scoped>
</style>

我正在尝试使用值 Importing 传递道具 message,但在加载组件中它告诉我 message 道具未定义。这是一个 REPREX:https://codesandbox.io/s/vibrant-raman-pweb4

我做错了什么?

【问题讨论】:

    标签: vue.js vuejs3 prop vue-props


    【解决方案1】:

    您正在尝试使用 v-bind: 速记语法将其传递给道具::

    Vue 期望你传入变量Importing。这不存在,所以它解析为未定义。

    因为您的消息只是一个内联字符串,您需要远程: 或用单引号或反引号包裹“导入”(如果您想要执行不够复杂的字符串插值以保证计算):

    <Loading message="Importing"></Loading>
    

    <Loading :message="'Importing'"></Loading>
    

    这也可以:

    <template>
      <Loading :message="message"></Loading>
    </template>
    
    <script>
    import Loading from "./components/Loading.vue";
    export default {
      name: "App",
      components: { Loading },
      data() {
        return {
          message: 'Importing',
        }
      }
    };
    </script>
    

    【讨论】:

    • 感谢您提供答案并澄清我做错的原因!
    • 不用担心,@Chris。很高兴有帮助。祝你好运!
    • 就像一个快速的旁注一样。你可以在 Vue 中使用自闭合标签来保持整洁。这是官方风格指南推荐的。所以 &lt;Loading message="Importing" /&gt; 而不是 &lt;Loading message="Importing"&gt;&lt;/Loading&gt; 以保持清洁
    猜你喜欢
    • 2021-06-06
    • 2021-06-27
    • 2022-08-20
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 2021-10-25
    相关资源
    最近更新 更多