Search code examples
javascriptvue.jsvuejs2vue-routervue-meta

How to update vue-meta on route/url change?


The meta data on my website is not updating when the route changes. The route itself has a watch on it which updates the view fine, but the metaInfo() from vue-meta is not keeping up. The <script> section of my code looks like this:

<script>
    export default {
        name: "Product",
        watch: {
            '$route.params.ProductID': {
                deep: true,
                immediate: true,
                handler() {
                    this.getProduct(); // calls getProduct() on route change. Can I also call metaInfo() from here somehow?
                }
            }
        },
        metaInfo() {
            return {
            title: this.Product.ProductTitle,
            meta: [
                {
                    name: 'description', content: this.Product.ProductTitle
                }
            ]
        }
        },
        computed: {
            Product() {
                return this.$store.getters.getProduct
            }
        }, mounted() {
            if (this.Product == null || !this.Product.length) {
                this.getProduct();
            }
        }, methods: {
            getProduct() {
                return this.$store.dispatch('loadProduct', {ProductID: this.$route.params.ProductID})

            } 
        }
    }
</script>

What is happening is that when I change my route and go from /product/123 to /product/124, the metaInfo() still shows the meta data for /product/123. If I hit refresh, then the metaInfo() updates and shows the correct data for /product/124.

I need the watch to trigger an update of metaInfo() but don't know how to do it. I can't find this information in the docs anywhere. Please help?


Solution

  • For reactive, use variables outside return statements.

    metaInfo() {
        const title = this.Product.ProductTitle;
    
        return {
            title: title,
            meta: [
                {
                    name: 'description', content: title
                }
            ]
        }
    }
    

    https://vue-meta.nuxtjs.org/guide/caveats.html#reactive-variables-in-template-functions