简体   繁体   English

vue 3 道具不传递给子元素

[英]vue 3 props are not passed to the child element

im a newbee, so help me someone please, im trying to pass an obj to child element as a prop, but i get an arr[0] val instead of {id: 1, name: 'General'}我是新手,所以请有人帮助我,我试图将 obj 作为道具传递给子元素,但我得到的是 arr[0] val 而不是 {id: 1, name: 'General'}

there i bind prop value, currentRoom is an const with Object.在那里我绑定道具值,currentRoom 是一个 const 与 Object。

<input-message :currentRoom="currentRoom"/>

currentRoom`s value is correct there and equals to {id: 1, name: 'General'} currentRoom 的值在那里是正确的,等于 {id: 1, name: 'General'}

in child element i try to get props that way:在子元素中,我尝试以这种方式获取道具:

const props = defineProps({
        currentRoom: Object
});

The whole code:整个代码:

container.vue容器.vue

<template>
 <AppLayout title="Dashboard">
     <template #header>
         <h2 class="font-semibold text-xl text-gray-800 leading-tight">
             Chat
         </h2>
     </template>

     <div class="py-12">
         <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
             <div class="bg-white overflow-hidden shadow-xl sm:rounded-lg">
                 <message-container :room="currentRoom"/>
                 <input-message :currentRoom="currentRoom" :customText="'blablabla'"/>
             </div>
         </div>
     </div>
 </AppLayout>
</template>

<script setup>
import AppLayout from '../../Layouts/AppLayout.vue';
import MessageContainer from "./messageContainer.vue";
import InputMessage from "./inputMessage.vue";
import {defineComponent} from "vue";

defineComponent([
 AppLayout,
 MessageContainer,
 InputMessage
])

let chatRooms = [];
let currentRoom = [];
let messages = [];

const getRooms = () => {
axios.get('/chat/rooms')
.then( response => {
   chatRooms = response.data;
   setRoom(response.data[0]);
})
.catch(error => {
   console.log(error);
})
}
const setRoom = (room) => {
 currentRoom = room;
<!-- if i console.log currentRoom here, it displayed correctly!!!! -->
 console.log(currentRoom)
 getMessages();
}
const getMessages = () => {
 axios.get('/chat/rooms/' + currentRoom.id + '/messages')
 .then(response => {
     messages = response.data;
 })
 .catch(error => {
     console.log(error);
 });
}
getRooms();
</script>

inputMessage.vue输入消息.vue

<template>
    <div class="relative h-10 m-1">
        <div style="border-top: 1px solid #e6e6e6;" class="grid grid-cols-6">
            <input
                type="text"
                v-model="message"
                @keyup.enter="sendMessage"
                placeholder="Say something..."
                class="col-span-5 outline-none p-1"
            />
            <button
                @click="sendMessage"
                class="place-self-end bg-gray-500 hover:bg-blue-700 p-1 mt-1 rounded text-white">
                Send
            </button>
        </div>
    </div>
</template>

<script setup>

    const props = defineProps({
        currentRoom: Object
        // customText: Text
    });
    console.log(props.currentRoom);
</script>

<style scoped>

</style>

UPDATE更新

You currentRoom data property is not reactive.您的currentRoom数据属性不是反应性的。 So, I guess, it triggers no updates to the props.所以,我想,它不会触发道具的更新。 You should define it this way:你应该这样定义它:

const currentRoom = reactive({});

or或者

const currentRoom = ref({});

In case of ref() you have then change the value of the ref like thisref()的情况下,您可以像这样更改refvalue

currentRoom.value = room;

Hope it helps.希望能帮助到你。


Your currentRoom is an Array.您的currentRoom是一个数组。 That's why you get [] in the console, when your array is empty.这就是为什么当你的数组为空时你在控制台中得到[]的原因。

Check your axios request if you get any data at all.如果您获得任何数据,请检查您的 axios 请求。 (Browser DevTools Network Tab) (浏览器 DevTools 网络选项卡)

Generally, you should pass one room item to your currentRoom prop or threat your prop as array.通常,您应该将一个房间物品传递给您的currentRoom道具或威胁您的道具作为数组。

Like this:像这样:

<table border=1>
  <tbody>
    <tr v-for="(room, index)  in props.currentRoom">
       <td>{{index}}</td>
       <td>{{room.id}}</td>
       <td>{{room.name}}</td>
    </tr>
  </tbody>  
</table>

Here is a working playground这是一个工作的游乐场

Just do it right way and it will work.只要以正确的方式去做,它就会奏效。

 const { createApp, ref } = Vue; const MyComponent = { props: { currentRoom: { type: Object, default: {} } }, setup(props) { console.log(`props.currentRoom: ${JSON.stringify(props.currentRoom)}`) }, template: `<div class="MyComponent">currentRoom: {{JSON.stringify(currentRoom)}}</div>` } const App = { components: { MyComponent }, setup() { const rooms = ref([]); const addRoom = () => { rooms.value.push( {id: rooms.value.length + 1, name: 'General'} ); } return { rooms, addRoom } } } const app = createApp(App) app.mount('#app')
 .MyComponent { border: 1px solid grey; padding: 12px; margin: 4px; }
 <div id="app"> App.rooms: {{rooms}}<hr/> rooms[0]: <my-component:current-room="rooms[0]"></my-component> rooms: <my-component v-for="room in rooms":current-room="room"></my-component> <button type="button" @click="addRoom()">Add Room</button> </div> <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM