如何强制更新Vue数据

时间:2019-12-23 01:04:26

标签: laravel vue.js

我在laravel中使用vuejs,当url更改时我有指向下一页和上一页的链接,但是新数据不会显示。

代码

Controller

$verse = Chapter::where('slug', $slug)->with(['verses', 'book'])->first();
$next = Chapter::where('id', '>', $verse->id)->first();
$previous = Chapter::where('id', '<', $verse->id)->first();
return response()->json([
  'verses' => $verse,
  'next' => $next,
  'previous' => $previous,
]);

component

<div v-if="previous !== null" :v-model="previous" class="bible-nav-button previous">
    <router-link :to="`/${testament_slug}/${book_slug}/${previous.slug}`">
        <i class="fas fa-chevron-left"></i> <span>Previous</span>
    </router-link>
</div>
<div v-if="next !== null" :v-model="next" class="bible-nav-button next">
    <router-link :to="`/${testament_slug}/${book_slug}/${next.slug}`">
        <span>Next</span> <i class="fas fa-chevron-right"></i>
    </router-link>
</div>

<script>
    export default {
        name: "books",
        data() {
            return {
                url: window.location.origin + "" + window.location.pathname,
                title: '',
                testament_slug:'',
                book_slug: '',
                slug: '',
                verses: [],
                next: '',
                previous: ''
            }
        },
        methods: {
            getBooks: function(){
                this.testament_slug = this.$route.params.testament_slug
                this.book_slug = this.$route.params.book_slug
                this.slug = this.$route.params.slug
                axios.get('/api/'+this.$route.params.book_slug+'/'+this.$route.params.slug+'/'+this.$route.params.slug).then((res) => {
                    this.verses = res.data.verses
                    this.title = "Read Bible: " +res.data.verses.book.name+ " " +res.data.verses.name
                    this.next = res.data.next
                    this.previous= res.data.previous
                })
                .catch((err) => {
                    console.log(err)
                });
            },
            myHTML: function(item) {
                return "<strong>"+item.number+"</strong> "+item.body+" ";
            }
        },
        mounted() {
            this.getBooks();
        }
    }
</script>

是否知道如何获取新数据?

2 个答案:

答案 0 :(得分:1)

您可以在:key标签中使用<router-view>道具并使用路径全路径。

<router-view :key="$route.fullPath"></router-view>

我曾经让当前路线的观察者和调用函数来获取数据,但是我发现在观看vueschool的vue-router教程之后我们可以做到这一点。

另请参阅此question

的答案

答案 1 :(得分:0)

您有两个简单的选择:

1)将“上一个”和“下一个”更改为再次单击fetch函数的@click操作,然后更新URL(例如this。$ router.push())。

<span @click="goNext(/* needed arguments here */)">Next</span>

goNext (/* params here */) {
     //set whatever variables you need to
     this.$router.push(/* route as string here */)
     this.getBooks()
}

2)由于您使用的是路由器,因此每次URL更改时都要使用防护措施进行更新: https://router.vuejs.org/guide/advanced/navigation-guards.html

beforeRouteUpdate(to, from, next) {
     this.getBooks()
     next()
}