vue获取路由的数据_使用Vue进行更高级的路由:数据获取

vue获取路由的数据

In the last post, More Advanced Routing with Vue, we covered using Transitions with Vue Router. This time we’ll cover Data Fetching with Vue Router.

在上一篇文章《 使用Vue进行更高级的路由》中 ,我们介绍了如何在Vue Router中使用Transitions 。 这次我们将介绍使用Vue Router进行 数据获取 。

Data Fetching allows us to load asynchronous data in our routed components. We can also specify whether data is fetched before or after a component is loaded. Both of these strategies are equally viable but have different implementations. We’ll cover both.

数据提取允许我们在路由的组件中加载异步数据。 我们还可以指定在加载组件之前还是之后获取数据。 这两种策略都同样可行,但是实现方式不同。 我们都将介绍。

Vue项目设置 (Vue Project Setup)

Since this is yet another post about advanced Vue Router techniques, we’ll assume you’re already familiar with the basic setup. However, let’s define a starting point that we’ll use for the rest of the post:

由于这是有关高级Vue路由器技术的另一篇文章,因此我们假设您已经熟悉基本的设置。 但是,让我们定义一个起点,我们将在本文的其余部分中使用该起点:

# Yarn
$ yarn add vue-router

# npm
$ npm install vue-router --save
main.js
main.js
import Vue from 'vue';
import VueRouter from 'vue-router';

import App from './App';
import Swamp from './components/Swamp';
import Gator from './components/Gator';

Vue.use(VueRouter);

const router = new VueRouter({
  routes: [
    { path: '/swamp', component: Swamp },
    { path: '/gator', component: Gator }
  ]
});

new Vue({
  render: h => h(App),
  router
}).$mount('#app')
App.vue
应用程序
<template>
  <div id="app">
    <div class="nav">
      <router-link to="/swamp">Swamp</router-link> |
      <router-link to="/gator">Gator</router-link>
    </div>
    <hr />
    <div class="router-view">
      <router-view></router-view>
    </div>
  </div>
</template>

<script>
export default { name: 'App' }
</script>
components/Swamp.vue
组件/Swamp.vue
<template>
  <div>Welcome to the Swamp, {{ name }}!</div>
</template>

<script>
export default {
  name: 'Swamp',
  data() {
    return { name: null }
  },
}
</script>
components/Gator.vue
组件/Gator.vue
<template>
  <div>Howdy, Gator {{ name }}!</div>
</template>

<script>
export default {
  name: 'Gator',
  data() {
    return { name: null }
  }
}
</script>

资料撷取 (Data Fetching)

Let’s say we had a function that mocked a simple HTTP GET called pretendGet():

假设我们有一个函数pretendGet()了一个简单的HTTP GET称为pretendGet()

scripts/pretendGet.js
脚本/ pretendGet.js
export default (callback) => {
  setTimeout(() => {
    callback(null, 'Alice');
  }, 500);
}

After 500ms pretendGet() will return the string 'Alice' to the callback method callback. We’ll use this to mock a server request in the following examples.

500毫秒后, pretendGet()将字符串'Alice'返回到回调方法callback 。 在以下示例中,我们将使用它来模拟服务器请求。

导航前获取 (Fetching before navigation)

Fetching before navigation allows us to ensure that our routed components have the data they need before being displayed to the user. In this approach we added a beforeRouteEnter method which Vue Router calls when the user requests to navigate to this component but before it has loaded. We also define a beforeRouteUpdate method which is called when the route changes. This is useful if you’re fetching data related to a route parameter which is accessible via to.params.

导航前获取使我们能够确保路由的组件在显示给用户之前具有所需的数据。 在这种方法中,我们添加了一个beforeRouteEnter方法,当用户请求导航到该组件但尚未加载该组件时, Vue Router会调用该方法。 我们还定义了一个beforeRouteUpdate方法,当路由更改时会调用该方法。 如果您要获取与可以通过to.params访问的route参数有关的数据,这将很有用。

components/Gator.vue
组件/Gator.vue
import pretendGet from '../scripts/pretendGet';

export default {
  name: 'Gator',
  data() {
    return { name: null }
  },
  // Component not loaded yet
  beforeRouteEnter(to, from, next) {
    pretendGet((err, name) => {
      next(vm => vm.setName(err, name));
    });
  },
  // Component already loaded and route changes
  beforeRouteUpdate(to, from, next) {
    this.name = null;
    pretendGet((err, name) => {
      this.setName(err, name);
      next();
    });
  },
  methods: {
    setName(err, name) {
      if (err) {
        console.error(err);
      } else {
        this.name = name;
      }
    }
  }
}

Keep in mind that navigation will not happen until data is fetched. Because of this, it’s a good idea to display some kind of progress bar or indicator that data is being fetched. If there’s an error, it would also be a good idea to display that as well.

请记住,在获取数据之前不会进行导航。 因此,最好显示某种进度条或指示正在获取数据的指示器。 如果有错误,最好也显示该错误。

导航后获取 (Fetching after navigation)

Fetching after navigation is also a valid approach. In this case we’ll utilize the created() lifecycle hook to call our data fetching method fetchName(). We’ll also define a watch property on $route so we can call fetchName() whenever the route changes.

导航后获取也是一种有效的方法。 在这种情况下,我们将利用created() 生命周期挂钩来调用数据获取方法fetchName() 。 我们还将在$route上定义watch属性,以便每当路由更改时都可以调用fetchName()

components/Swamp.vue
组件/Swamp.vue
import pretendGet from '../scripts/pretendGet';

export default {
  name: 'Swamp',
  data() {
    return { name: null }
  },
  created() {
    this.fetchName();
  },
  watch: {
    // Re-fetch when route changes
    '$route': 'fetchName'
  },
  methods: {
    fetchName() {
      pretendGet((err, name) => {
        if (err) {
          console.error(err);
        } else {
          this.name = name;
        }
      });
    }
  }
}

Keep in mind that with this approach we’ll have to account for data not being ready when the component is first rendered. It’s a good idea to include placeholders or skeleton placeholders along with indicators to let the user know that data is being fetched along with any errors that might occur.

请记住,使用这种方法时,我们必须考虑到首次渲染组件时尚未准备好数据。 最好将占位符或框架占位符以及指示符包括在内,以使用户知道正在提取数据以及可能发生的任何错误。

结语 (Wrapping Up)

Vue Router Data Fetching is a great way to ensure a smooth user experience for your components that rely on fetching data from external sources. Fetching before navigation is a good approach if you’re a fan of using app-wide notifications or progress indicators. If you’d rather handle this kind of stuff on a component level then fetching after navigation might be the right approach for you. As always, make sure to read the docs!

Vue路由器 数据获取是确保依赖于从外部源获取数据的组件的流畅用户体验的绝佳方法。 如果您喜欢使用应用程序范围的通知或进度指示器,那么在导航之前进行获取是一种不错的方法。 如果您希望在组件级别上处理此类工作,那么导航后获取可能是适合您的正确方法。 与往常一样,请务必阅读文档

翻译自: https://www.digitalocean.com/community/tutorials/vuejs-routing-data-fetching

vue获取路由的数据

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值