nuxt-jsonld

repository·master·Indexed 43 days ago

https://github.com/ymmooot/nuxt-jsonld

A Nuxt module for managing and injecting JSON-LD structured data within Vue components. Compatible with Nuxt 3 and Nuxt 4, it provides the useJsonld composable for the Composition API and a jsonld() method for the Options API. It supports reactive data, custom tag positioning via tagPosition, and conditional rendering.

Tokens
2.8K
Snippets
13
Records
14
Agent score
54%

What's inside nuxt-jsonld

  1. How to provide multiple JSON-LD objects

    master

    To include multiple JSON-LD datasets from a single component, you can return an array of objects from useJsonld.

    Note on Safari Compatibility: Safari may log an error to the console when an array is used to describe multiple data objects. While the library functions correctly, it is recommended to use the @graph notation instead to avoid these console errors and ensure cleaner error logging in tools like Sentry.

    // Using an array (Note: may cause Safari console errors)
    useJsonld([
      {
        '@context': 'https://schema.org',
        '@type': 'BreadcrumbList',
        itemListElement: [/* ... */],
      },
      {
        '@context': 'https://schema.org',
        '@type': 'NewsArticle',
        mainEntityOfPage: { /* ... */ },
      },
    ]);
    
    // Recommended approach to avoid Safari errors: Use @graph notation
    useJsonld({
      '@context': 'https://schema.org',
      '@graph': [
        { '@type': 'BreadcrumbList', /* ... */ },
        { '@type': 'NewsArticle', /* ... */ },
      ]
    });
  2. Hide JSON-LD conditionally

    master

    If you want to prevent a JSON-LD tag from being rendered under certain conditions (e.g., when data is missing), simply return null from your useJsonld call.

    <script lang="ts" setup>
    useJsonld(() => {
      if (!props.product) {
        return null;
      }
      return {
        '@context': 'https://schema.org',
        '@type': 'Product',
        name: props.product.name,
      };
    });
    </script>
  3. Install nuxt-jsonld

    master

    You can install nuxt-jsonld using the Nuxt CLI, which automatically registers the module in your nuxt.config.ts:

    $ npx nuxi module add nuxt-jsonld

    Alternatively, you can install it manually using your preferred package manager and add it to the modules array in nuxt.config.ts:

    // nuxt.config.ts
    export default defineNuxtConfig({
      modules: ['nuxt-jsonld'],
    });
  4. Configure disableOptionsAPI

    master

    Since the Options API jsonld method is implemented using a global mixin, you can disable it in your nuxt.config.ts if you only intend to use the Composition API. This is useful for reducing overhead if the feature is unused.

    // nuxt.config.ts
    export default defineNuxtConfig({
      modules: ['nuxt-jsonld'],
      'nuxt-jsonld': { disableOptionsAPI: true },
    });
    
    // Or using the array syntax:
    export default defineNuxtConfig({
      modules: [['nuxt-jsonld', { disableOptionsAPI: true }]],
    });
  5. Use the Options API with jsonld() method

    master

    In the Options API, you can define a jsonld() method in your Vue component. This method should return the structured data object. This feature is implemented via a global mixin.

    <script lang="ts">
    import type { WithContext, BreadcrumbList } from 'schema-dts';
    
    export default defineComponent({
      data() {
        return {
          breadcrumbs: [
            { url: 'https://example.com', text: 'top page' },
          ],
        };
      },
      jsonld(): WithContext<BreadcrumbList> {
        return {
          '@context': 'https://schema.org',
          '@type': 'BreadcrumbList',
          itemListElement: this.breadcrumbs.map((item, index) => ({
            '@type': 'ListItem',
            position: index + 1,
            item: {
              '@id': item.url,
              name: item.text,
            },
          })),
        };
      },
    });
    </script>
  6. Use useJsonld with Composition API

    master

    The useJsonld composable allows you to manage JSON-LD within Vue components using the Composition API. It is available via auto-imports, but can also be explicitly imported from #jsonld.

    You can pass a static JSON object or a function that returns a JSON object to enable reactivity.

    Tag Position

    You can control where the JSON-LD tag is placed in the document using the tagPosition option. Supported values are 'head' (default), 'bodyOpen', and 'bodyClose' (appends to the end of the <body> tag).

    <script lang="ts" setup>
    // Static JSON-LD
    useJsonld({
      '@context': 'https://schema.org',
      '@type': 'Thing',
      name: 'static json',
    });
    
    // Reactive JSON-LD
    const count = ref(0);
    useJsonld(() => ({
      '@context': 'https://schema.org',
      '@type': 'Thing',
      name: `reactive json: count is ${count.value}`,
    }));
    
    // Custom tag position
    useJsonld(
      {
        '@context': 'https://schema.org',
        '@type': 'Thing',
        name: 'static json',
      },
      {
        tagPosition: 'bodyClose', // 'head', 'bodyOpen', 'bodyClose'
      }
    );
    </script>
  7. Configure nuxt-jsonld module options

    master

    The nuxt-jsonld module can be configured in your nuxt.config.ts using the nuxt-jsonld key. The primary configuration option is disableOptionsAPI.

    If disableOptionsAPI is set to true, the module will not register the plugin that enables the Options API usage (e.g., using jsonld as a component option).

    export interface ModuleOptions {
      disableOptionsAPI: boolean;
    }
    
    // Example usage in nuxt.config.ts:
    export default defineNuxtConfig({
      modules: ['nuxt-jsonld'],
      nuxtJsonld: {
        disableOptionsAPI: true
      }
    });
  8. Use the useJsonld composable to manage JSON-LD

    master

    The useJsonld composable allows you to inject JSON-LD structured data into your Vue components. It automatically handles the creation of a <script type="application/ld+json"> tag using @unhead/vue.

    You can pass either a static JSON object or a function that returns a JSON object. Using a function allows the JSON-LD to be reactive, updating whenever the function's internal dependencies change.

    import { useJsonld } from 'nuxt-jsonld';
    
    // Using a static object
    useJsonld({
      '@context': 'https://schema.org',
      '@type': 'WebSite',
      'name': 'My Site'
    });
    
    // Using a function for reactivity
    useJsonld(() => ({
      '@context': 'https://schema.org',
      '@type': 'Product',
      'name': props.productName
    }));
  9. Use JSON-LD with the Vue Options API

    master

    By default, nuxt-jsonld allows you to provide JSON-LD data directly as a component option named jsonld. This is enabled unless disableOptionsAPI is set to true in your module configuration.

    Note: This feature extends the ComponentCustomOptions interface in Vue.

    <script>
    export default {
      jsonld: {
        '@context': 'https://schema.org',
        '@type': 'Article',
        // ... other properties
      }
    }
    </script>
  10. Use the useJsonld composable

    master

    The module automatically provides the useJsonld composable, which can be imported and used within your Vue components to manage JSON-LD data.

    // useJsonld is auto-imported by the module
    const { setJsonld } = useJsonld();
    
    setJsonld({
      '@context': 'https://schema.org',
      '@type': 'WebPage',
      // ... other properties
    });