Vue组件中的Prop无React性

brccelvz  于 2023-04-07  发布在  Vue.js
关注(0)|答案(1)|浏览(187)

要么我对Vue.js有一个基本的误解,要么我发现了一个bug。我能够在下面的最小示例中重现这个bug(?)。
组件App.vue有一个React式的message变量,它作为一个prop传递给子Child.vue。这个消息可以通过一个按钮来改变。这很好用。但是,当你在Child中提醒消息时,你总是会得到第一条消息-它根本没有更新。看起来消息只在标记中更新,而不是在JavaScript中。我真的被这种行为搞糊涂了。

App.vue

<script setup>
import { ref, computed } from "vue";
import Child from "./components/Child.vue";

let index = ref(0);
let messages = ["hi", "there", "this", "is", "strange"];

let message = computed(() => messages[index.value]);

function change_message() {
    index.value++;
    if (index.value === messages.length) {
        index.value = 0;
    }
}
</script>

<template>
    <Child :message="message"></Child>
    <div>
        <button @click="change_message">Change message</button>
    </div>
</template>

Child.vue

<script setup>
const { message } = defineProps(["message"]);
function alert_message() {
    window.alert(message);
}
</script>

<template>
    <h1>
        {{ message }}
    </h1>
    <button @click="alert_message">Alert message</button>
</template>

Demo

有一个解决方案:不要破坏Child中的props。因此编写const props = defineProps(["message"]);,然后使用window.alert(props.message);。然而,在现实世界的Vue应用程序中,这将导致代码非常臃肿。我不想一直携带props.

u2nhd7ah

u2nhd7ah1#

当你破坏 prop 时,你失去了React性,对于你的情况,一种方法可以使用参考:
Child.vue

<script setup>
import { toRefs } from "vue";

const props = defineProps(["message"]);
const { message } = toRefs(props);

function alert_message() {
  window.alert(message.value);
}
</script>

<template>
  <h1>
    {{ message }}
  </h1>
  <button @click="alert_message()">Alert message</button>
</template>

https://codesandbox.io/s/nameless-water-jwhw90?file=/src/components/Child.vue
无论如何,在需要时使用props.<your_prop>是一个标准,即使是在现实世界的Vue应用程序中

相关问题