V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
juventusryp
V2EX  ›  问与答

求教 vue3 下路由传参给子组件后,子组件列表如何能实时渲染

  •  
  •   juventusryp · 2022-12-05 11:47:28 +08:00 · 577 次点击
    这是一个创建于 501 天前的主题,其中的信息可能已经有所发展或是发生改变。

    描述:

    • 想在 message.vue 中点击 button 按钮后向子组件的数组中传入一个值,然后在子组件 detail.vue 的页面中能够实时的渲染显示。
    • 知道肯定要向 detail.vue 中的 messageList 数组中 push 传入的参数,但是不知道具体怎么写,特来求教,先行谢过。
    // message.vue
    <template>
      <li v-for="m in messageList" :key="m.id">
        <router-link
          :to="{ name: 'Detail', query: { id: m.id, title: m.title } }"
          >{{ m.title }}</router-link
        >
        <button @click="pushShow(m)">push 查看</button>
      </li>
      <hr />
      <router-view></router-view>
    </template>
    
    <script setup lang="ts">
    import { ref, reactive } from "vue";
    import { useRoute, useRouter } from "vue-router";
    let messageList = [
      { id: "004", title: "message004" },
      { id: "005", title: "message005" },
      { id: "006", title: "message006" },
    ];
    
    const router = useRouter();
    
    const pushShow = (m: { id: string; title: string }) => {
      router.push({ name: "Detail", query: { id: m.id, title: m.title } });
    };
    </script>
    
    <style scoped lang="less"></style>
    
    
    // detail.vue
    <template>
      <li v-for="m in messageList" :key="m.id">
        {{ m.title }}
      </li>
    </template>
    
    <script setup lang="ts">
    import { ref, reactive, onMounted } from "vue";
    import { useRoute } from "vue-router";
    
    let messageList = reactive([
      { id: "001", title: "message001" },
      { id: "002", title: "message002" },
      { id: "003", title: "message003" },
    ]);
    
    const route = useRoute();
    </script>
    
    <style scoped lang="less"></style>
    
    
    4 条回复    2022-12-05 15:15:07 +08:00
    sjhhjx0122
        1
    sjhhjx0122  
       2022-12-05 13:47:46 +08:00
    最简单的就是,messageList 并不在 detail 里维护,detail 只渲染单条,在 message.vue 维护 messageList ,然后循环 detail props 传入单条数据
    leoQaQ
        2
    leoQaQ  
       2022-12-05 14:16:39 +08:00
    用 watch ?
    hevi
        3
    hevi  
       2022-12-05 14:38:13 +08:00
    onMounted 的时候,把传进来的值 push ,然后消除 query
    或者 watch ,push 后消除 query
    yigecaiji
        4
    yigecaiji  
       2022-12-05 15:15:07 +08:00 via Android
    不用 push ,用 set ?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   863 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 21:42 · PVG 05:42 · LAX 14:42 · JFK 17:42
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.