Home » vue » Access global computed properties in <script> tag

Access global computed properties in <script> tag

Posted by: admin November 26, 2021 Leave a comment

Questions:

Vuepress defines some global properties than can be used in templates, like $page or $site.

https://github.com/vuejs/vuepress/blob/master/packages/docs/docs/guide/global-computed.md

I can use these within the <template> node, but trying to use them within <script> throws an error.

<template>
  <div class="page">
    <div class="content">
      <div>{{ $page.frontmatter.description }} Works fine</div>
      <div>{{ $frontmatter.description }} Does not work despite what's in docs</div>
      <div>{{ description }} Doesn't work</div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return { 
      description: this.$page.frontmatter.description, //not defined
      description2: $page.frontmatter.description, //nor this
    };
  },
};
</script>
Answers:

Your problem is not about using Vuepress Global Computed Properties inside <script> tag, it’s actually about using Vuejs Computed Properties inside data().

If you simply create a Vue component like the code snippet below, you will find the variable testMessage is not defined either.

<template>
  <div>{{ testMessage }}</div>
</template>

<script>
export default {
  data() {
    return {
      testMessage: this.test
    }
  },
  computed: {
    test: function() {
      return 'This is a test';
    }
  }
}
</script>

I don’t know the exact reason for this, but I believe it’s about the lifecycle of Vue instance. So I suggest you simply access the Global Computed Properties inside computed properties or methods:

<template>
  <div>{{ description }}</div>
</template>

<script>
export default {
  computed: {
    description : function() {
      return this.$page.frontmatter.description;
    }
  }
}
</script>