在 vue 中将 prop 从父组件传递到子组件不起作用

问题描述 投票:0回答:1

我目前有一个带有 CompositionAPI 的小型 Vue 项目,但现在遇到了问题。 我有一个父组件和两个子组件。子组件用于显示所有用户(其中还有删除和编辑用户的选项)。另一个子组件用于编辑用户。

流程是这样的:用户按下 edit user,然后在父组件中触发一个方法,其中也传递了要编辑的用户的 ID,然后将该 ID 作为 prop 传递给第二个子组件(然后发出 API 请求来加载和插入所有用户数据)。 这一切都按预期工作,但是父组件中的用户 ID 仍然是正确的,然后不再在子组件中(它始终是未定义的)。

我已经尝试了 v-bind 和 ‘:’ 的所有方法,但我不知道还能做什么。有趣的是,如果我在 :edit-user-id 中输入像 10 这样的数字,那么一切都会完美运行,但前提是我想再次使用该变量。我希望有人能帮助我。代码在这里:

用户列表视图.vue

<script setup>
  const emit = defineEmits(['update-user']);

  function pressEdit(id) {
    emit('update-user', id);
  }

  function fetchAllUsers(){
    // all User get fetched here
  }
</script>

<template>
  <button class="button" v-on:click="pressEdit(user.userid)">Edit</button>
</template>

管理视图.vue

<script setup>
  let isEditActive = ref(false);
  let editUserId = ref();

  function userUpdateDone(){
    isEditActive.value = false;
    userlistBinding.value.fetchAllUsers();
  }

  function userUpdatePress(id) {
    editUserId.value = id;
    isEditActive.value = true;
  }
</script>

<template>
 <Userlistview ref="userlistBinding" @update-user="userUpdatePress($event)"/>

 <Usereditview v-if="isEditActive" :edit-user-id="editUserId.value" @update-user= "userUpdateDone()"/>
</template>

用户编辑视图.vue

<script setup>
  const props = defineProps({editUserId: Number});
  const emit = defineEmits(['update-user']);

  function loadUser() {
    // here get the user loaded with the specific id from the props
  }

  function updateUser() {
    // here gets the user updated -> if the respone is ok then this line of code will be executed
    emit('update-user');
  }
</script>
javascript vue.js vuejs3 vue-component
1个回答
0
投票

参考文献自动在模板中展开

value
需要省略:

:edit-user-id="editUserId"
© www.soinside.com 2019 - 2024. All rights reserved.