vue2之 missing param for named route "xxxx"

本文介绍如何在Vue.js中使用路由并处理异步数据加载的问题,通过将router-link置于v-if条件判断中,避免在数据未准备好时尝试渲染。示例代码展示了如何为Bar组件异步获取笑话数据。

场景:

解决方法:可以做的是将其包含router-link在适当的位置v-if,以便在您的异步数据实际到达之前不会尝试渲染。

html代码:

<div id="app" class="container">
  <p>
    <router-link to="/foo">Go to Foo</router-link>
    <router-link to="/bar">Go to Bar</router-link>
  </p>
  <router-view></router-view>
</div>

<script  type="text/x-template" id="joke">
    <div class="container">
         bar  <br>
       <template v-if="joke"> 
           {{joke.joke}}
           <router-link :to="{name: 'joke', params: {number: joke.id}}">{{joke.id}}</router-link>
    </template>
  </div>
</script>

js

const Foo = { template: '<div>foo</div>' }
const Bar = { 
  template: '#joke',
  data () {
    return {
      joke: null
    }
  },
  methods: {
    get: function () {
      this.$http.get('https://api.icndb.com/jokes/random').then((response) => {
        this.joke = response.body.value
        console.log(this.joke)
      }, (response) => {
        console.log(response)
      });
    }
  },
  mounted () {
    this.get()
  }
}
const funny = {
  template: '<div> {{id}}</div>',
  computed: {
    id () {
      return this.$route.params.number
    }
  }
}

const routes = [
  { 
    path: '/foo', 
    component: Foo,
    name: 'foo'
  },
  { 
    path: '/bar', 
    component: Bar,
    name: 'bar'
  },
  {
    path: '/joke/:number',
    name: 'joke',
    component: funny
  }
]

const router = new VueRouter({
  routes 
})

const app = new Vue({
  router
}).$mount('#app')

 

转载于:https://www.cnblogs.com/raind/p/9274732.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值