【问题标题】:Fetching data using different routes but using same component VueJS 3使用不同的路由但使用相同的组件VueJS 3获取数据
【发布时间】:2021-03-06 10:14:22
【问题描述】:

请检查此代码: 它基本上显示了两条路由,使用从 API 消费内容的相同组件。

Main.js

const router = createRouter({
    history: createWebHistory(),
    routes: [
        {
            path: "/route1",
            name: "Route1",
            component: BaseContent,
            meta: {
                title: 'Route 1'
            }
        },
        {
            path: "/route2",
            name: "Route2",
            component: BaseContent,
            meta: {
                title: 'Route2'
            }
        }
    ]
});

BaseContent.vue

  <base-section v-for="entry in this.entries" :key="entry" lang="lang-markup" :title="entry.title">
  <template v-slot:content>
      <div v-html="entry.content"></div>
  </template>
    <template v-slot:examples>
      <div v-html="entry.examples"></div>
    </template>
    <template v-slot:code>
        {{entry.code}}
    </template>
  </base-section>
</template>

<script>
export default {
  mounted(){
    this.$nextTick(function () {
    Prism.highlightAll();
    this.getData()
  })
  },
    
  updated(){
    this.$nextTick(function () {
    Prism.highlightAll();
    this.getData()
  })
  },
  methods:{
    getData(){
      const url= 'https://example.dev/api/collections/get/'+this.$route.name+'?token=XXXXXXXXX'
    
    fetch(url)
    .then(collection => collection.json())
    .then(collection => {

      const entries = [];

            for (const id in collection.entries) {
              entries.push({
                title: collection.entries[id].Title,
                content: collection.entries[id].Content,
                examples: collection.entries[id].Examples,
                code: collection.entries[id].Code,

              });
            }

            this.entries = entries;

    });
    }
  },
  data() {
    return {
      entries:[]
    };
  },
};
</script>

问题: 此解决方案有效。但有两件事让我抓狂。 1st - 内容的行为方式很奇怪,当我单击链接以遵循这些路线中的任何一条时,内容会在两条路线内容之间闪烁,然后才能实际呈现正确的内容 2nn - 如果我打开开发工具,我会看到内容在不断更新(开发工具代码选项卡上的部分标签一直闪烁紫色,表示更新)。

关于我做错了什么的任何提示?

PS:我是 VUE JS 的新手。

非常感谢!!!

问候, T.

【问题讨论】:

    标签: javascript vue.js vue-router vuejs3


    【解决方案1】:

    我已经设法解决了这个问题。 经过一番挖掘,我发现我所需要的只是为我的App.vue 文件中的&lt;router-view&gt; 组件提供一个唯一的:key 标识符。

    所以我刚刚添加了这个:

    &lt;router-view :key="$route.fullPath"&gt;&lt;/router-view&gt;

    它解决了这个问题,因为 Vue 的反应系统知道它需要再次重新加载整个组件,因为键是唯一的,而在它不是之前。

    希望能帮助其他人!

    问候, T.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-18
      • 2016-08-17
      • 1970-01-01
      • 2019-06-11
      • 2021-01-08
      • 2016-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多