What is the best way to alternate between displaying HTML content with v-html and plain text in Vue.js?

I need a way to switch between v-html and plain text in Vue.js v2. Here's what I have so far:

HTML

<div id="app">
  <h2 v-html="html ? text : undefined">{{html ? '' : text}}</h2>
  <button @click="toggle">
    switch
  </button>
</div>

JS

new Vue({
  el: "#app",
  data: {
    text:"Hello<br/>World",
    html:false
  },
  methods: {
    toggle: function(){
        this.html = !this.html;
    }
  }
})

This code does not work when html is false. Can anyone suggest a solution that avoids repeating the <h2> tag using v-else? Ideally, I would like to achieve this with just one <h2> tag.

Thank you!

Answer №1

To apply the v-bind using the prop modifier, you can check out the documentation.

new Vue({
  el: "#app",
  data: {
    text:"Hello<br/>World",
    html:false
  },
  computed: {
    headingProps() {
      return this.html ? { innerHTML: this.text } : { innerText: this.text } ;
    },
  },
  methods: {
    toggle: function(){
        this.html = !this.html;
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
  <h2 v-bind.prop="headingProps"></h2>
  <button @click="toggle">
    switch
  </button>
</div>

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

Preventing the insertion of a line break when using Shift + Enter in Vuejs

Whenever I use a textarea to enter text, I find that I have to press Shift + Enter every time to send the text. However, upon sending, it adds /n at the end. I prefer using the Enter key for newline instead of submitting the form. Example: hello => ...

Launching a new tab with a specific URL using React

I'm attempting to create a function that opens a new tab with the URL stored in item.url. The issue is, the item.url property is provided by the client, not by me. Therefore, I can't guarantee whether it begins with https:// or http://. For insta ...

Incorporating a full-page background into a specific view using AngularJS

In order to implement a fullscreen CSS background for a specific view in my app, I attempted adding a class to the body. However, this approach caused the background to persist in the cache and remain visible when switching views. The challenge arises fro ...

What is the best way to manage HTML code that is delivered through JSON data?

I am dealing with data from a JSON that is in HTML code format. I need to print it as HTML, but currently it is only printing as a string: "content": "More tests\u003cbr /\u003e\n\u003cbr /\u003e\n\u003cdiv class=&bso ...

Retrieve JSON object from dropdown menu

I need to retrieve the object name from a dropdown menu when an item is selected. How can I access the object from the event itemSelect? Thank you for your attention. View Dropdown Menu XML code: <core:FragmentDefinition xmlns="sap.m" xmlns:c ...

Leveraging the results from a static React function

I am currently working on a React + Webpack project that supports JavaScript ECMAScript 6. Here is the code snippet I am trying to implement: class ApiCalls extends React.Component{ static uploadFiles(files) { // upload code if(success) { ...

Having trouble with the Bootstrap dropdown not activating the click event?

My issue involves a Bootstrap dropdown where the click event is not triggering. I'm curious about why the click event won't trigger and if there's a solution available to fix this problem. <div class="dropdown d-inline-block"> ...

Is there any variation in the Stripe payments Workflow when utilizing the Connect-API?

I have a question about simplifying the implementation of the Stripe API for multiple products on a single page. Currently, I have a webpage with 20 different items and I am utilizing Stripe Connect. Instead of creating individual forms for each product i ...

Can you explain the purpose of App.hiddenDivs in jQuery code snippet provided?

Exploring various JQuery performance tips on this insightful website Do you happen to know the significance of App.hiddenDivs ? ...

Send a form without the need to reload the page

I have a form that inserts values into the database successfully. However, each time the values are submitted, the page refreshes. I attempted to find a solution on this website, but it didn't work for me. Can someone please advise me on how to submit ...

"Utilize Ajax to dynamically generate options in a dropdown menu with multiple

I am having trouble populating my multiple dropdown list using AJAX. The dropdown list is dependent on another single selection dropdown list. Here is the HTML code: <div class="form-group"> <label for="InputGender">Select Course</ ...

Utilize querySelectorAll to inspect class properties

When exporting a table to CSV, I have implemented the following logic: var cols = rows[i].querySelectorAll("td, th"); While this method works well, users are able to hide/display columns as they desire. Since AngularJS is used, the hidden columns are mar ...

Introducing Vue.js - the powerhouse of named slots feature for

Having trouble with named slots in my beginner example. Specifically, I'm trying to display only the content for the first slot, but it doesn't work unless I use <slot></slot> without specifying name="first". Any insights on what migh ...

Ensuring the validation of JSON schemas with dynamically generated keys using Typescript

I have a directory called 'schemas' that holds various JSON files containing different schemas. For instance, /schemas/banana-schema.json { "$schema": "http://json-schema.org/draft-06/schema", "type": "object", "properties": { "banan ...

Guide to retrieving a specific cookie value with socket.io

I have successfully retrieved all cookies using the socket.request.headers.cookie. Upon console logging, the output appears as follows: PHPSESSID=mtklg8k81cpkop5ug6aechbb34; user=77; io=1Klg6xgTRXhb2OWiAAAA Now, I am trying to extract only the value of ...

Issue with ng-bind-html in TranslateJS causing problems

I have been working on implementing translation in a web application using angularJS and the angular-translate repository, which can be found at . As per the documentation, it is possible to use this repository to set text for a specific element in the HTM ...

JavaScript problem with hovering action causing additional buttons to appear

Currently, I am developing a user interface where, upon hovering over an LI element, 2 buttons appear to provide additional functionality - "edit" and "remove". However, I am facing challenges with the mouse hit zones. The mouseover function works effect ...

Stopping a NodeJS script execution: Tips and Tricks

While working on my NodeJS application, I've noticed that occasionally my CPU usage spikes to 100%, but there is no memory variation. This causes my Event Loop to become blocked by the operation. I recalled how browsers handle problematic scripts by ...

Having difficulty applying a style to the <md-app-content> component in Vue

Having trouble applying the CSS property overflow:hidden to <md-app-content>...</md-app-content>. This is the section of code causing issues: <md-app-content id="main-containter-krishna" md-tag="div"> <Visualiser /> </md-app ...

Struggling to organize and paginate numbers in angularjs and facing filtering and sorting issues

I'm running into some issues with getting the paging feature to work properly while applying filters. Currently, when the filters are active, the paging numbers do not display correctly and only filter the first page of results. What I'm aiming ...