【问题标题】:vuejs3: how to init a ref using a prop?vuejs3:如何使用道具初始化 ref?
【发布时间】:2023-01-29 13:47:01
【问题描述】:

我有这个代码

<script setup>

defineProps({
  position: { type: String, required: false, default: "center middle" },
});

</scritp>

我在尝试

const myPosition = ref(position);

但我得到了

Uncaught (in promise) ReferenceError: position is not defined

我做错了什么,重要的是,为什么?

【问题讨论】:

  • 它被清楚地记录在in the docs(不要忘记选择左侧栏上的组合 API 切换以查看组合 API 的文档)

标签: vuejs3 vue-composition-api vue-script-setup


【解决方案1】:

要使用“组件”API 和 &lt;script setup&gt; 初始化道具,您需要为 defineProps(...) 宏返回的对象分配一个名称,例如 props 并在引用脚本中的道具时使用该变量名称.所以如果你有一个像这样声明的道具:

const props = defineProps({
  position: { type: String, required: false, default: "center middle" },
});

您可以像这样在同一个脚本中使用它:

const myLocation = ref(props.position);

因此,一个完整的示例可能如下所示:

父组件.vue

<template>
  <div class="main-body">
    <h1>Parent Component</h1>

    <div class="grid-container">
      <div>
        Position (in Parent):       
      </div>
      <div>
        <input v-model="msg">
      </div>
    </div>
    <hr>
    <div>
        <Child :position="msg" title="Child Component 1"/>
    </div>
    <div>
        <Child  title="Child Component 2 (default position property)"/>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import Child from './Child.vue'

const msg = ref('North West')
</script>

<style>
  .main-body {
    margin: 10px 20px;
  }
  .grid-container {
    display: grid;
    grid-template-columns: 1fr 2fr;
  }
</style>

然后 儿童.vue

<template>
    <h2>
    {{ title }}
  </h2>
  <div class="grid-container">
    <div>
      Position (from parent): 
    </div>
    <div>
      {{ position }}
    </div>
    <div>
      My Position: 
    </div>
    <div>
      <input type="text" v-model="myLocation">
    </div>
    <div>
      My Position: 
    </div>
    <div>
      {{ myLocation }}
    </div>
  </div>
  
</template>

<script setup>
import { ref } from 'vue';

const props = defineProps({
  position: { type: String, required: false, default: "center middle" },
  title: { type: String, required: false, default: "ChildComponent"}
});
const myLocation = ref(props.position);  
</script>

<style scoped>
  .grid-container {
    display: grid;
    grid-template-columns: 1fr 2fr;
  }
</style>

另外,请在 Vue Playground 中查看此代码

在这个例子中,myPosition 字段是用 prop 初始化的,但是一旦应用程序启动,这个字段就不再依赖于 prop。

【讨论】:

    【解决方案2】:

    起初,您的代码还不够完整。你在哪里尝试const myPosition = ref(position);

    如果您定义了您的props权利,那么就没有必要向他们申请refreactive。他们已经反应了。

    现在只需在组件中使用你position

    这是来自 Vue 教程步骤 12 Props 的示例

    <!-- ChildComp.vue -->
    <script setup>
    const props = defineProps({
      msg: String
    })
    </script>
    

    <ChildComp :msg="greeting" />
    

    【讨论】:

      猜你喜欢
      • 2018-08-31
      • 2019-05-10
      • 1970-01-01
      • 1970-01-01
      • 2019-05-03
      • 2016-02-14
      • 2021-03-24
      • 1970-01-01
      • 2020-06-23
      相关资源
      最近更新 更多