0

我正在从我的 vue-router 中获取一个参数,并且在尝试将参数数据存储到我的组件数据中时出现此错误

Error in created hook: "TypeError: Cannot read property 'params' of undefined"

这是我从('Home')组件发送数据的地方

<template>
  <div class="container">

      <div v-for="art in articles" :key="art.title">
          <img alt="an image">
          <h4>{{art.title}}</h4>
          <button @click="shareData()"></button>
      </div>

  </div>
</template>

<script>
//const fb = require('../../fireconfig.js')

export default {
  name: 'Home',
  data:function() {
    return{
       articles: [
         {
           title: 'eee',
           body: 'oooo',
           img: 'dd'
        },
         {
           title: 'eesecone',
           body: 'secondddd',
           img: 'dwwd'
        }
      ]
    }
  },
  props: {
    post: Object
  },
  created(){
    console.log('db post will go here later')
    /*
    let ref = fb.db.collection('articles')
    ref.get()
  .then(snapshot => {
    if (snapshot.empty) {
      console.log('No matching documents.');
      return;
    }  
    snapshot.forEach(doc => {
      console.log(doc.id, '=>', doc.data());
      this.articles.push(doc.data())
    });
  })
  .catch(err => {
    console.log('Error getting documents', err);
  });
  */
  },
  methods:{
    shareData(){
      this.$router.push({name: 'Article', params: {data: this.articles} })
    }
  }
}
</script>

这是接收数据并存储它的组件('Article'),它们在同一个目录中

<template>
  <div class="container">
      <h3>THIS IS THE PAGE FOR A SINGLE ARTICLE</h3>
  <div v-for="art in articleData" :key="art.title">
      <img alt="an image">
          <h4>{{art.title}}</h4>
          <div>{{art.body}}</div>
</div>


  </div>
</template>

<script>
export default {
  name: 'Article',
    data:function(){
        return{
        articleData:[]
        }
},
    created(){
        this.articleData = this.$routes.params.data  //----------error happens here-------------
    }
}
</script>

这是我在 main.js 中的路由器设置 :)

import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router';
import Article from './components/Article.vue'
import Home from './components/Home.vue'
import Search from './components/Search.vue'
Vue.use(VueRouter)
const routes = [
  {
    path: '/Article',
    name: 'Article',
    component: Article,
  },
  {
    path: '/',
    name: 'Home',
    component: Home,

  },
  {
    path: '/Search', component: Search,
    props: true
  }
];
const router = new VueRouter({
  routes
})

Vue.config.productionTip = false

new Vue({
  router,
  render: h => h(App),
}).$mount('#app')

4

1 回答 1

0

您要添加的s应该$route是:

this.$route.params.data

this 指的是当前路由,而不是所有 $routes 或 $router

于 2020-05-30T00:30:57.797 回答