Vue3:sounds属性无法随数据库更新及子组件文件名Prop传递问题
Vue3中
sounds无法同步数据库数据更新的解决方案 核心问题分析
你当前的代码存在三个关键错误:
- 在
<script setup>语法中,不能通过定义const computed普通对象来创建计算属性,必须使用Vue官方提供的computed函数。你现在写的computed只是一个普通对象,Vue不会识别它为响应式计算属性,自然无法触发数据同步。 <script setup>不存在组件实例的this上下文,this.mcollection1Data的写法完全无效,根本取不到响应式变量的真实值。- 你一开始声明了
soundsref,但后续的无效computed定义完全没和它关联,导致sounds始终停留在初始的空数组状态。
修复步骤
- 从Vue导入
computed函数(当前代码仅导入了ref和onMounted)。 - 删除无用的
soundsref声明和无效的const computed对象,用computed函数创建可读写的响应式计算属性sounds。
修改后的完整代码
<script setup> import { ref, onMounted, computed } from 'vue'; // 新增computed导入 import axios from 'axios'; import playsound from './playsound.vue' const collection1Data = ref([]); const collection2Data = ref([]); const mcollection1Data = ref([]); const mcollection2Data = ref([]); // 替换原有的sounds ref和无效computed对象 const sounds = computed({ get() { return mcollection1Data.value; // 直接访问响应式变量,无需this }, set(value) { mcollection1Data.value = value; } }); const fetchData = async () => { const [collection1Response, collection2Response] = await Promise.all([ axios.get('https://koh-xyn.com:50100/onboardshows'), axios.get('https://koh-xyn.com:50100/onboardlands'), ]); collection1Data.value = collection1Response.data; collection2Data.value = collection2Response.data; const currentTime = new Date().getTime(); const filteredData1 = collection1Response.data.filter(doc => { const updatedTime = new Date(doc.updatedAt).getTime(); return currentTime - updatedTime < 20 * 1000; }); const filteredData2 = collection2Response.data.filter(doc => { const updatedTime = new Date(doc.updatedAt).getTime(); return currentTime - updatedTime < 20 * 1000; }); mcollection1Data.value = filteredData1; mcollection2Data.value = filteredData2; }; onMounted(() => { fetchData(); setInterval(fetchData, 1000); }); const isRecentlyUpdated = (updatedAt) => { const updatedTime = new Date(updatedAt); return (Date.now() - updatedTime.getTime()) < 15000; }; </script>
额外说明
现在sounds会自动同步mcollection1Data的变化,将其作为Prop传递给子组件时,直接在模板中写:
<playsound :sounds="sounds" />
子组件就能实时接收到更新后的数据。
内容的提问来源于stack exchange,提问作者Nopmd
相关产品推荐
相关产品推荐

