Guide on how to swap a string with a component in Vue

I have a string that contains placeholders ### and I want to replace them with values from an array. I created a component, but I'm not sure how to incorporate it into the string since the number of placeholders can vary. For instance, if there are 2 ### in the string, the options array will have 2 subArrays.

What is the best approach for this scenario?

Code: https://jsfiddle.net/tsobh4nu/

Vue.component('opt', {
  template: `<label>
                <span class="bold" v-for="(str,idx) in options">
                     {{str + " / "}}
                </span>
             </label>`,
  props:{options: Array}
})

new Vue({
  el: '#app',
  data: {
    str: "I have ### and you have a ###.",
      options: [
        ['AAA', 'BBB', 'CCC'],
        ['XXX', 'YYY', 'ZZZ']
      ]
  },
  computed:{
  replacedStr(){
    let newStr = this.str;
      this.options.forEach(option=>{
      newStr = newStr.replace('###',this.concatenateOptions(option));
      })
      return newStr;
    }
  },
  methods: {
    concatenateOptions(strArr) {
      let separator = "";
      let strOptions = "";
      strArr.forEach(word => {
        strOptions += separator  + word;
        separator = " / ";
      });
      return strOptions;
    }
  }
})
.bold {
  font-weight: bold
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
  <p>I want something like this, but using components: </p>
  {{replacedStr}}
  <br>
  <hr>
  My Components:<br>
  <opt :options="options[0]"></opt>
  <br>
  <opt :options="options[1]"></opt>
</div>

Thank you!

Answer №1

If you're looking for a more general solution, here's something that might be of help to someone out there. Start by incorporating a dynamic component into your template:

<component v-bind:is="processedHtml"></component>
.

Next, introduce a computed method:

computed: {
    processedHtml () {
        let html = this.html.replace('[Placeholder]', '<my-component></my-component>');
        return {
            template: '<div>' + html + '</div>'
        }
     }
}

In the above code snippet, <my-component> refers to your custom component, while this.html should contain your HTML content with the placeholder [Placeholder].

Make sure to always return an element that has one root node, hence why the return statement is enclosed within <div>.

For a more detailed guide on this topic, feel free to check out my blog post here. It covers advanced techniques, such as passing props to <my-component>.

Answer №2

Recently, I encountered a similar issue where I needed to display the current count of an item on a webpage. The count was retrieved from a store and it was constantly changing. To accomplish this, I utilized the v-text attribute. While this solution may be specific to my scenario, I hope it can benefit others facing similar challenges in the future.

<P id="results_count" v-text="current_count"></P> 

Within the data section of the component, I included a property named current_count that was continuously updated using methods.

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

The function res.render is not displaying the new page

I have a task that seems straightforward. On my header, I am loading a few a links. <a class="nav-link" href="menu">Menu 1</a> I am attempting to access the URL /menu from this link. In my app.js file: app.use('/', index); app.us ...

What steps should I take to address the issues with my quiz project?

I've been working on a new project that involves creating a quiz game. I came across some code online and decided to customize it for my needs. However, I'm encountering some issues with the functionality of the game. Right now, the questions ar ...

Language setting required for dijit.form.DateTextBox

I am attempting to create a calendar control dynamically using Dojo 1.5 and set the language to Spanish, but so far I have been unsuccessful. I tried using "lang:es-es" among other things with no success... here is the element: <input type="text" const ...

Trouble displaying MongoDB data on Meteor template

As I embarked on building my first app with Meteor, everything seemed to be going smoothly until I encountered an issue where a collection was no longer displaying in a template. Here is the code snippet: App.js Tasks = new Mongo.Collection("tasks"); i ...

Is there a way to activate button A when button B is clicked in VueJS?

Xyz.vue <v-flex xs12 sm6> <v-btn class="changeNumberBtn" disabled @click="changeNumber()">Change Number</v-btn> </v-flex> <v-btn round block color="green darken-3" dark large @click="generateCode ...

The error message 'ReferenceError client is not defined' is indicating that the

I'm currently attempting to retrieve the id of clients connecting to my socket.io/node.js server by following the method outlined in the top response on how to get session id of socket.io client in Client. However, I am encountering an error message: ...

How can I attach the input value that has been selected to another div using Ajax AutoComplete for jQuery?

Greetings, I am currently utilizing the Ajax AutoComplete for jQuery library. Within this library, there are 2 demos available. In the first demo titled "Ajax auto-suggest sample (start typing country name)", when a country is selected from the dropdown, ...

Node.JS Error: "util.TextEncoder is not a constructor" was thrown

After using browserify to bundle my js files, I encountered an error that says Uncaught TypeError: util.TextEncoder is not a constructor at Object.1.util (bundle.js:3) at o (bundle.js:1) at r (bundle.js:1) at bundle.js:1 Below are the init ...

The SVG animation is reversing and decreasing in size from the bottom

Feeling lost, I spent a day searching without success. I have a project in full Vuejs and I thought using Svg would be easy and fun, but I can't figure out why the image resizes when playing an animation. The bottom of the svg seems to resize and get ...

Creating a wrapper component to enhance an existing component in Vue - A step-by-step guide

Currently, I am utilizing quasar in one of my projects. The dialog component I am using is becoming redundant in multiple instances, so I am planning to create a dialog wrapper component named my-dialog. my-dialog.vue <template> <q-dialog v-bin ...

Whenever attempting to detach(), I am encountering the following error message: local.ERROR: Call to a member function programs() on an integer

I am dealing with a Many to Many relationship between Courses and Programs. The insertion of new courses and adding multiple programs works correctly. However, the issue arises during updates. When I update a course, I want to detach all related programs a ...

Fade background when the youtube video in the iframe begins playing

Hey there! I'm looking to create a cool effect on my (wordpress) site where the background dims when a YouTube video starts playing. The video is embedded in this way: <iframe frameborder="0" width="660" height="371" allowfullscreen="" src="https ...

What is the best way to securely store my API key within a Vue.js application?

I recently reviewed the Vue CLI documentation and I wanted to confirm my understanding. According to the documentation, It is important to note that only NODE_ENV, BASE_URL, and variables beginning with VUE_APP_ will be included in the client bundle usin ...

What is the best way to incorporate the final paragraph into the foundational code?

I'm attempting to create my own version of the lyrics for 99 Bottles of Beer Here is how I've modified the last line: 1 bottle of beer on the wall, 1 bottle of beer. Take it down and pass it around, no more bottle of beer on the wall. How ...

Guide on converting a timestamp output in Node.js

I ran a query to retrieve TimeStamp data from MYSQL using Node JS, and the output is as follows: MyDate: Thu Apr 28 2016 07:02:45 GMT+0700 (SE Asia Standard Time) Can anyone help me convert it to yyyy-mm-dd hh:mm:ss format? ...

How to incorporate Laravel includes within a Vue component?

Having a collection of components, with some components incorporating other components through @include('my-sub-component') The problem lies in the fact that when I try to implement vue, I am required to place the whole component within the temp ...

Troubleshooting: Why isn't my Vue v-for list updating when using v

I have a basic application that retrieves data from an API and displays the array on the screen using a v-for loop. The array is structured like this items : [{id : 1, quantity: 2}, {id: 2, quantity: 3} ...] The loop is set up like this <div v-for=&qu ...

Unexpected Behavior: using setTimeout in a ReactJS class component leads to incorrect value retrieval

App Component: class App extends React.Component { constructor() { super(); this.state = { user: 'Dan', }; } render() { return ( <React.Fragment> ...

iOS devices are experiencing issues with touchstart and touchend events not functioning when utilizing jquery mobile and cordova

During a previous project, I encountered no problems with the following code snippet. It effectively utilized touchstart and touchend events to adjust the CSS of a button: <script> $('input[type="button"]').on('touchstart', func ...

Utilize a for loop in Vue.js to save a fresh array of objects in a structured format

Trying to achieve the following using Vue: I have two JSON objects that provide information on languages and the number of inputs per language. Using nested loops, I display all the inputs. My goal is to create an object for each input with additional det ...