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

Combining Turn.js with AJAX for an interactive web experience

I've been experimenting with turn.js and struggling to find an example of loading dynamic pages with content via ajax. While the page is loading, it's not displaying all the results. For a JSON result from the controller, click here. <div clas ...

Arranging objects in an array based on a separate array of strings

Here is an array of objects that I need to rearrange: var items = [ { key: 'address', value: '1234 Boxwood Lane' }, { key: 'nameAndTitle', value: 'Jane Doe, Manager' }, { key: 'contactEmail', value: ...

What is the best way to separate a comma-delimited string in JS without including JSON data?

I have a string that looks like this: ABC, CDE, [{"ab":"1","cv":"23"},{"ab":"1","cv":"2%3A1639251967619%2C%22v%22%3A1%7D"}] My goal is to split it into an array of length 3, w ...

Leveraging kazupon/vue-i18n within a Vuex module

Utilizing the Vue-i18n Library for Localization The functions Vue.t() || $t() || trans() expect a string as a key to be translated by vue-i18n Hello everyone! I'm currently experimenting with the code below: import Vue from 'vue' expor ...

Safeguarding intellectual property rights

I have some legally protected data in my database and I've noticed that Google Books has a system in place to prevent copying and printing of content. For example, if you try to print a book from this link, it won't appear: How can I protect my ...

How to Pass Values in handleChange Event in Typescript

I have noticed that most online examples of handling change events only pass in the event parameter, making the value accessible automatically. However, I encountered an error stating that the value is not found when trying to use it in my handleChange fun ...

Encountering a "Module not found" error when trying to integrate NextJs 13.4 with React Query and the

I encountered some issues while working on a NextJs application that utilizes App Router. The problem arose when we decided to switch from traditional fetching to using React Query in server components. To address this, I created a file called api.ts withi ...

Issue with sending functions to other components in Angular

I'm currently facing an issue with passing functions to other objects in Angular. Specifically, I've developed a function generateTile(coords) that fills a tile to be used by leaflet. This function is located within a method in the MapComponent. ...

Retrieve webpage content using an ajax request in JavaScript

I'm working on an HTML page with an Ajax call to load table content. <html> .... <script sec:haspermission="VIEW_NOTE" th:inline='javascript'> require(['app/agent/viewGlobalAgent'], function (){ ...

Accessing a variable from an external JavaScript file using jQuery

Can someone help me out with this issue I'm facing? I am having trouble getting a string returned to a variable in my embedded Javascript code. token.js: function token () { return "mysecretstring"; } HTML Code: <!DOCTYPE html> <h ...

Vue lightweight loading CSS error: "Undefined property 'denominator'"

Within my project, I have a style.less file that I am loading in the following manner: import "./styles/styles.less"; The contents of the file are structured as shown below. I had to encapsulate the styles to prevent them from affecting the rest of the p ...

What is the level of visibility in Nextjs?

Is it safe to expose the sources of files located in the 'pages/' directory? For instance, if you set up a page specifically for administrators at pages/admin and restrict access through Middleware, does this enhance security measures? ...

I am experiencing an issue where localhost is not displaying the JSON output for the Router and controller that I have

Recently delving into the world of NodeJS, I find myself facing a roadblock. While attempting to manage requests, my localhost appears to be endlessly loading or throwing an error. Error: cannot GET/ I aim to showcase the JSON data on my local site. Wh ...

Problem importing npm module with Meteor 1.3

I've been trying to follow the guide for using npm packages in Meteor 1.3, particularly focusing on installing the moment npm module. However, I can't seem to work it out despite its simplicity. Every time I attempt to use the package in the cli ...

Interacting with iView UI dropdown menu items

I'm attempting to create a click event in iView ui. Here's my code: <DropdownMenu slot="list"> <DropdownItem @on-click="markAsRead">Mark as read</DropdownItem> </DropdownMenu> The function markAsRead isn't exec ...

Tips on working with an array received from a PHP script through AJAX

I've been stuck with this issue for the past few hours and I'm hoping to find a solution here. What I'm attempting to do is something like the following: PHP: $errorIds = array(); if(error happens){ array_push($errorIds, $user['user ...

"Troubleshooting VueJS: Issue with default value not being set in

Trying to set a default value for a select in Vue. <script src="https://unpkg.com/vue"></script> <div id="app"> <select v:model="select"> <option value="1">1</option> <option value="2">2</optio ...

The background image of my bootstrap carousel is not responsive to changes in the browser window size

Hey there, I'm new to the world of programming and currently working on a project to create the front end of my personal website. I've opted to utilize a bootstrap carousel background image slider in my index.html file. However, I've noticed ...

Implement CSRF protection for wicket ajax requests by adding the necessary header

I'm currently working on a website created with Apache Wicket and we're looking to enhance its security by implementing CSRF protection. Our goal is to keep it stateless by using a double submit pattern. For forms, we are planning to include a h ...

Inserting items into an array entity

I am attempting to insert objects into an existing array only if a certain condition is met. Let me share the code snippet with you: RequestObj = [{ "parent1": { "ob1": value, "ob2": { "key1": value, "key2": va ...