Vue.js does not display HTML properly within the vue-swal component

I'm currently working on integrating HTML content into a Sweet Alert popup using this code snippet

Link: https://www.npmjs.com/package/vue-swal

  this.$swal({
      title: '<i>Custom HTML</i>',
  html:`This is an <em> emphasized text </em>, <a href="#">links</a><strong>And other tags</strong>`,
  showCloseButton: true,
  showCancelButton: true,
  focusConfirm: false,
});

However, I am facing an issue where the HTML content is not being rendered properly. The title is visible but even within the title, the HTML is not rendered as expected.

Output: https://i.stack.imgur.com/5wz4A.png

Answer №1

For a different approach, consider utilizing the content attribute instead of using title and html

// Create wrapper element to retrieve RatingComponent as a pure DOM node
let wrapper = document.createElement('div');

// Shared state
let state = {
    note: 0
}

// Create component for content
let SampleComponent = Vue.extend({
    data() {
    return {rating: 0}
  },
  watch: {
    rating (newVal) { state.note = newVal }
  },
    template: `
    <div class="rating">
      <div><i><b> My Title </b></i></div>
        <p>This is an <em> emphasized text </em>, <a href="#">links </a><strong>And other tags</strong></p>
    </div>`,
})

let component = new SampleComponent().$mount(wrapper)

Vue.component('job', {
  template: '<button class="btn" @click="rate">Click me!</button>',
  methods: {
    rate() {
      this.$swal({
        content: component.$el,
        buttons: {
            confirm: {
            value: 0
          }, 
            close: {
            value: 1
          },
          cancel: {
            value: 1
          }
        }
      }).then(() => {
        this.$swal('Please accept and give an upvote if this answer helped');
      })
    }
  }
});

//Create a new Vue instance and attach it to our div element with the id of app
var vm = new Vue({
  el: '#app'
});
body {
  font-family: Helvetica Neue, Arial, sans-serif;
  font-size: 14px;
  color: #444;
}

.rating {
  padding: 30px 0 0 0;
}

.vue-star-rating {
    margin: 20px auto;
}

.btn {
  display: inline-block;
  margin-bottom: 0;
  font-weight: 400;
  text-align: center;
  vertical-align: middle;
  -ms-touch-action: manipulation;
  touch-action: manipulation;
  background-color: #42b983;
  cursor: pointer;
  color: #fff;
  border: 1px solid transparent;
  white-space: nowrap;
  padding: 6px 12px;
  font-size: 14px;
  line-height: 1.42857;
  border-radius: 4px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/vue-swal"></script>
<div id="app">
  <job></job>
</div>

Answer №2

It's recommended to use content for inserting HTML tags instead of mixing HTML and text in the alert message. For more information, you can refer to

showAlert() {
  const template = `Add your custom text here <strong'>Text</strong>`;
  this.$swal({
    content: {
      element: "i",
      attributes: {
        innerHTML: `${template}`,
      },
    },
  });
},

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

Parent component does not receive Vue.js $emit when multiple calls are made in rapid succession

Recently, I attempted to create a basic notification system utilizing the Notification Store concept influenced by Linus Borg's code snippet available at: https://jsfiddle.net/Linusborg/wnb6tdg8/ The functionality works flawlessly when adding notifi ...

Tips for including an element at the start while creating a map()

enum StatusEnum { accepted = "AC", rejected = "RJ", } const select = (Object.keys(StatusEnum) as Array<keyof typeof StatusEnum>).map((x) => ({ value: x, name: x + "_random", })) /** * Console.log(select) * [ ...

Overcome the issue of 'Parsing Error: Kindly verify your selector. (line XX)' in Javascript/AWQL

Hello there! Just to clarify, I am not a developer and my coding skills are limited to basic HTML. Your patience is greatly appreciated ...

trigger a border hover effect on an HTML element

Is it possible to attach a mouseover event specifically to the left border of a div element in HTML? The div serves as a container for various other intricate HTML elements, each with their own mouseover events. While binding a mouseover event to the enti ...

Creating a targeted jQueryUI tab focus

My jQueryUI tabs have a click function defined on a specific tab which works correctly with ajax calls: $("a[href='#tabs-1ua']").click(function (event, ui) { //ajax call }); Now I want to capture not just clicks but any type of focus on thi ...

Achieving a collapsing navbar on click in Bootstrap 5

Is there a way to collapse this navigation bar after clicking on a link, without using a JavaScript event listener or the data-bs-toggle and data-bs-target methods mentioned in this article? I tried both methods but they are not working with my code. Here ...

What is the best way to view and use the data stored within this JSON object?

Obtaining information from a straightforward API (). I retrieve the data using getJSON: var police = $.getJSON(queryurl); A console.log on police displays this: However, I am unable to access the properties within the object. I assumed that I could ac ...

What could be causing my JSON product list to not load properly?

My list is not loading and I can't figure out why. I've included my json, jquery, and HTML below. The console isn't showing any errors, but the list is still blank. Any help would be greatly appreciated as I am new to working with json. Than ...

Content displayed in the center of a modal

Struggling to center the captcha when clicking the submit button. Check out the provided jsfiddle for more details. https://jsfiddle.net/rzant4kb/ <script src="https://cdn.jsdelivr.net/npm/@popperjs/<a href="/cdn-cgi/l/email-protection" class=" ...

Having difficulties obtaining sorted results for an e-commerce website API using Node.js

I have implemented logic to sort products based on query parameters sent by the user const getAllProduct = asynchandler( async ( req, res)=>{ try { // filter the products search const queryObj ={...req.query}; const excludef ...

How can you retrieve the `categoryIds` key within an object that holds an array of mongodb's `ObjectId(s)` as its value?

In my Node.js code, I have the following: var getQuestionsByUserId = function (config) { var query = { _id: ObjectId(String(config.userId)) }; var projection = { categoryIds: true, _id: false }; var respondWithCategories = function (error, doc ...

Changing the key name for each element in an array using ng-repeat: a guide

In my current project, I have an array of objects that I am displaying in a table using the ng-repeat directive. <table> <thead> <tr> <th ng-repeat="col in columnHeaders">{{col}}</th> //['Name&apo ...

What could be causing the constant undefined response when using ajax to post to php?

I have been using a mouseover event on a span element to trigger an ajax post call to a php page. However, I keep getting undefined values - first for responseText when using a simple echo to get the response, and now with responseXML. Can someone please h ...

Tips for incorporating JSON data into an HTML table

https://i.sstatic.net/WEdge.jpgIn an attempt to showcase JSON data in an HTML table, I want the schoolClassName value to be displayed as a header (th) and the first names of students belonging to that specific schoolClass to appear in a column beneath the ...

Invoking an AJAX function that is not inside the document.ready function

I'm having trouble populating a Google Map and here's some of the code I'm using. The ajax request doesn't seem to be working properly. When I put everything inside document.ready() as an anonymous function, it works fine. However, sinc ...

What steps can I take to resolve the issue in my code? I keep receiving a type error stating that it cannot read

I seem to be encountering an issue when running my code where I receive a 'cannot read property 'age' of null'. This error breaks my code, and I'm trying to figure out how to implement a check to ensure it only runs when I am signe ...

Creating a wrapper function for the map method in React

When attempting to incorporate a parameter into my map function in React, I encountered an issue where the return value turned null after encapsulating it within another function. This became apparent during debugging, especially when using console.log(mar ...

Inquiring about browserify or webpack on a website using node - a few queries to consider

Seeking assistance with a website project I am currently working on. The project consists of 7 HTML documents, 3 stylesheets, 8 JavaScript files (including jQuery.min.js and some additional jQuery plugins), and various images. I am looking to bundle and mi ...

React: Render function did not return any content. This typically indicates that a return statement is missing

Can anyone help me troubleshoot this error? Error: CountryList(...): No render was found. This typically indicates a missing return statement. Alternatively, to display nothing, return null index.js import React from 'react'; import ReactDOM f ...

Using Page.ResolveClientUrl in JavaScript or jQuery allows for easy resolution of client

I find myself in a predicament where I need to choose between using an HTML page instead of a .aspx page for performance reasons. Currently, I am using an aspx page solely because of the CSS and javascript file paths like: <script type="text/javascript ...