Utilizing Vue and Prismic rich text: incorporating an event listener onto a span element

In my Vue app, I am retrieving content from Prismic using an API CMS. Within this content, there are certain sections enclosed in span tags with a unique class. My goal is to target those specific span nodes in Vue and apply an event listener to them.

When attempting to accomplish this task with vanilla JavaScript, the following code would suffice:

var selectedSpanElements = document.querySelectorAll('.className');
selectedSpanElements[0].style.color = "red"

However, when implementing this code in Vue, it appears to only work momentarily before Vue refreshes the DOM. Experimenting with various hooks such as mounted, beforeupdate, updated, and ready did not yield successful results.

Update: After some time, I discovered that by utilizing the HTMLSerializer, I can insert HTML code into the span tags. Nonetheless, this method only allows for standard HTML insertion and does not grant access to Vue methods.

Answer №1

@Bruja I found a solution using a closure after getting some help from the team at Prismic.

It's worth noting, as mentioned by Phil Snow in the comment above, that if you're working with Nuxt, you might need to resort to traditional JavaScript instead of relying on Vue's functionality.

Take a look at this example where you can pass component-level props, data, methods, and more to the prismic htmlSerializer:

<template>
  <div>
    <prismic-rich-text
      :field="data"
      :htmlSerializer="anotherHtmlSerializer((startNumber = list.start_number))"
    />
  </div>
</template>
import prismicDOM from 'prismic-dom';

export default {
  methods: {
    anotherHtmlSerializer(startNumber = 1) {
      const Elements = prismicDOM.RichText.Elements;
      const that = this;

      return function(type, element, content, children) {
        // For additional elements and customizations, refer to:
        // https://prismic.io/docs/vuejs/beyond-the-api/html-serializer

        that.testMethod(startNumber);

        switch (type) {
          case Elements.oList:
            return `<ol start=${startNumber}>${children.join('')}</ol>`;
        }

        // Return null to maintain default behavior for everything else
        return null;
      };
    },

    testMethod(startNumber) {
      console.log('test method here');
      console.log(startNumber);
    }
  }
};

Answer №2

It seems like you're heading in the right direction by exploring the HTML Serializer. To ensure that all .specialClass <span> elements trigger a click event calling specialmethod(), you can implement the following:

import prismicDOM from 'prismic-dom';

const Elements = prismicDOM.RichText.Elements;

export default function (type, element, content, children) {
  // Check if the element classname is "specialClass"
  if (type === Elements.span && element.className === "specialClass") {
    return `<span @click="specialMethod">${content}</span>`;
  }

  // Return null for default behavior
  return null;
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

ag grid - issue with icons not appearing correctly

<script> import {AgGridVue} from "ag-grid-vue"; import 'ag-grid-enterprise'; import 'ag-grid-community/dist/styles/ag-grid.scss'; import "ag-grid-community/dist/styles/ag-grid.css"; import "ag-grid-community/dist/styles/ag-theme-a ...

What are the best practices for effectively utilizing the nodejs Stream API?

I am currently working on an application that reads input from various sources, including files, sockets, and other parts of the same program that produce buffers or strings. While I have successfully handled sockets and files using node's Stream API ...

Utilizing a JavaScript function to toggle the Bootstrap dropdown without the need for manual clicking

I've configured a Bootstrap dropdown in my site's mini cart that includes a lightbox effect to grey out the background content when the dropdown is activated. Here's the code snippet: $(".dropdown").on('show.bs.dropdown hide.bs.dropdow ...

Is there a way to prevent the URL of my Next.js app from constantly changing?

Our current Next.js project requires that the static URL remains constant, even when navigating between pages. This is a client requirement that we must adhere to. Can you provide suggestions on how we can achieve this? Maintaining the same URL throughout ...

Fusion of Laravel and Vue component

I am trying to connect a Vue component using a tag MyComponent.vue <template> <div> <h1>Hey there!</h1> </div> </template> <script> export default { } </script> This is the content of app. ...

Steps to open specifically the WhatsApp application upon clicking a hyperlink, image, or button

I need a code for my HTML website that will open the WhatsApp application when a user clicks on a link, image, or button while viewing the site on a mobile device. Only the WhatsApp application should be opened when a user interacts with a link on my webs ...

What is the connection between tsconfig.json and typings.json files?

I recently acquired a .NET MVC sample application that came with Angular2-final. Within the project, I noticed a typings.json file at the root and a tsconfig.json file in the ng2 app directory. What is the connection between these two files? Is this the mo ...

Troubleshooting Angular: Unidentified property 'clear' error in testing

I've implemented a component as shown below: <select #tabSelect (change)="tabLoad($event.target.value)" class="mr-2"> <option value="tab1">First tab</option> <op ...

When attempting to access http://localhost:3000/highLightTitle.png using Next.js, a 404 error (Not Found) was encountered in the content

Despite not having any mention of GET http://localhost:3000/highLightTitle.png in my Next.js project code, I am encountering an error related to this issue. The error can be viewed here, and specifically at line 199 in content.js which can be seen here. T ...

Unable to access Session state in Web Service through ajax on the client side

I'm facing an issue where the system is generating a new session for each user when I run an ajax query, instead of having just 1 session per user. Strangely, there were no issues when I tested it in debug mode on my computer, but problems arose on th ...

How can I design a versatile button in HTML/CSS3/jQuery/Javascript that utilizes images for borders and corners for maximum scalability?

Is there a way to create a completely scalable button in HTML/CSS3/jQuery+Plugins using images for borders and corners? I have attempted a messy method, but I am confident that there are more effective solutions available. The approach I considered invol ...

Issue with fading out in Ajax.BeginForm not resolving

I currently have: @using (Ajax.BeginForm("actionToDo", new AjaxOptions { HttpMethod = "post", InsertionMode = InsertionMode.Replace, UpdateTargetId = "updatediv", OnBegin = "$('#updatediv').fadeOut()", OnComplete = "$(&apo ...

Google Maps integrated AWS server

While utilizing an AWS server for my application, I have encountered a difficulty with Google Maps. When running my application using localhost, Google Maps functions perfectly fine. However, when attempting to run the application using an IP address, it f ...

How can I navigate through a webpage using Selenium WebDriver and JavaScript?

Currently, I am utilizing the JavaScript API for selenium-webdriver and my goal is to scroll/move down a page in a gradual manner to facilitate visual inspection. Although I am aware that the code below will direct me immediately to a link at the end of t ...

The suspense fallback function seems to be missing in NextJS 13

I'm in the process of creating an application to demonstrate the functionality of Suspense in Nextjs 13. However, I'm encountering an issue where the Suspense fallback is not appearing during loading. Below is the code for page.js import React, ...

Divergence in results: discrepancy found in the outputs of nodejs crypto module and tweetnacl.js

Consider this code snippet in nodejs: import crypto from 'crypto'; const pkey = `-----BEGIN PRIVATE KEY----- MC4CAQAwBQYDK2VwBCIEIJC52rh4PVHgA/4p20mFhiaQ/iKtmr/XJWMtqAmdTaFw -----END PRIVATE KEY-----`; // placeholder key function sign_message(m ...

Automatically logging in to a website using an AngularJS form

I am struggling with autologin to a website that has an authentication form built with Angular JS. The form structure looks like this: <form name="loginForm" class="login-form ng-pristine ng-invalid ng-invalid-required"> <div class="tight-fo ...

What is the process for sending a request to a static resource along with parameters?

I currently have a node.js restify server running, along with a folder containing static resources. const restify = require('restify') let server = restify.createServer() server.listen(8080, function () { console.log('%s listening at ...

Performing an AJAX request from a subfolder

Can anyone help me figure out how to make an ajax request from a page located in a subdirectory and receive a response? On my webpage, index.jsp is situated within a subdirectory called /vf2. In this page, there is a script file included: <script src=" ...

What are the common issues with Angular 2's ng-if directive?

I am completely new to working with Angular and have already gone through all the ng-if related questions without finding a solution that fits my issue. Here is my code: <tr *ngFor="#position of positions"> <td> ...