Невозможно установить данные, извлеченные с помощью ловушки beforeRouteEnter - vuesj2 - PullRequest
0 голосов
/ 07 мая 2018

У меня есть компонент статьи:

<template>
      <article class="content">
          <div class="content__inner">
              <h1 v-html="post.title" class="content__title"></h1>
                <div :style="{ backgroundImage: 'url(' + post.image + ')' }" class="content__img"></div>
                <div class="content__meta">
                    <h5>by {{post.author}}</h5>
                    <h5>{{post.date}}</h5>    
                </div>
                <div v-html="post.content" class="content__text"></div>
          </div>
          <app-share></app-share>
          <!--<related :post="{category:post.categories,id:post.id}"></related>-->
  </article>

</template>

<script>
import Share from './Share.vue';
import RelatedPosts from './RelatedPosts.vue';
import axios from 'axios';
export default {
name:'article-gy',
components:{
    appShare:Share,
    related:RelatedPosts
},
  data(){
      return{
        post:{}
      }
  },
  created(){
      console.log('inside created',this.post)
     //this.$on('changeContent', post => {
          //this.post = post
          //document.body.scrollTop = document.documentElement.scrollTop = 0;
          //this.$router.push('/'+this.post.slug)
          //sessionStorage.setItem('currentPost',JSON.stringify(this.post))
      //})
  },
  destroyed(){
      //sessionStorage.removeItem('currentPost')
  },
  beforeRouteEnter(to,from,next){
      if(to.params.post){
        next(vm=>{
            vm.post.id = to.params.post.id
            vm.post.content = to.params.post.content.rendered
            vm.post.image = to.params.post.better_featured_image.source_url
            vm.post.author = to.params.post.post_author
            vm.post.date = to.params.post.date
            vm.post.title = to.params.post.title.rendered
            vm.post.categories = to.params.post.categories
            sessionStorage.setItem('currentPost',JSON.stringify(vm.post)) 
            console.log('inside next',vm.post.id) 
          })
      }
      else{
          axios.get('/posts?slug='+to.path)
          .then(response => response.data[0])
          .then(post =>{
              next(vm =>{
                  vm.post.content = post.content.rendered
                  vm.post.author = post.post_author
                  vm.post.image = post.better_featured_image.source_url
                  vm.post.date = post.date
                  vm.post.title = post.title.rendered
                  vm.post.categories = post.categories
                  vm.post.id = post.id
                  sessionStorage.setItem('currentPost',JSON.stringify(vm.post))
                  console.log('inside next',vm.post.id)
            })
        })
    }  
  }
}
</script>

в хуке beforeRouteEnter Я пытаюсь установить некоторые данные с условием if else, если первое условие применяется, это означает, что пользователь пришел с другой страницы, которая принадлежит веб-сайту, эта страница передает некоторые данные через объект params.

В другом случае я делаю другой запрос, чтобы получить правильные данные поста, относящиеся к слагу.

Теперь кажется, что данные выбираются, но не отображаются в шаблоне. В созданном хуке, если я консоль регистрирую переменную записи, я фактически вижу данные, но я не знаю, почему данные записи не отображаются.

Странная вещь: если я это сделаю, в созданном хуке:

console.log(this.post)

Я получаю данные, но если, например, я получу:

console.log(this.post.id)

Я не определен.

Это не происходит внутри следующего, где я получаю правильные данные, даже если я консоль журнала post.id

Как это возможно?

Спасибо

EDIT

Я пробовал другое решение, избегая хука beforeRouteUpdate и работая только с хуком created:

created(){
     //this.$on('changeContent', post => {
          //this.post = post
          //document.body.scrollTop = document.documentElement.scrollTop = 0;
          //this.$router.push('/'+this.post.slug)
          //sessionStorage.setItem('currentPost',JSON.stringify(this.post))
      //})
      if(this.$route.params.post){
          this.post.id = this.$route.params.post.id
            this.post.content = this.$route.params.post.content.rendered
            this.post.image = this.$route.params.post.better_featured_image.source_url
            this.post.author = this.$route.params.post.post_author
            this.post.date = this.$route.params.post.date
            this.post.title = this.$route.params.post.title.rendered
            this.post.categories = this.$route.params.post.categories
      }else{
          //console.log(this.$route.params.slug)//

          axios.get('/posts?slug='+this.$route.params.slug)
            .then(response => response.data[0])
                .then(post=>{
                    this.post.id = post.id
                    this.post.content = post.content.rendered
                    this.post.image = post.better_featured_image.source_url
                    this.post.author =  post.post_author
                    this.post.date = post.date
                    this.post.title = post.title.rendered
                    this.post.categories = post.categories
                    console.log('inside then',this.post)
                })
      }
  },

но не работает в любом случае, если маршрут содержит объект post в this.$route.params, содержимое загружается, в противном случае содержимое извлекается через axios, но не отображается

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...