assign a dynamic expression to a variable

I am currently working on a Vue application where an expression is retrieved from a config file as a variable. My goal is to run this expression (similar to using eval in JavaScript) and apply the result to an attribute.

For example:

<v-text-field placeholder="{{expression}}"></v-text-field>

However, instead of evaluating the expression, it is simply displaying as text. Is there a way to make this work?

Edit


In this case, the expression may look like:

data.option=1?"ABC":"BCD"

Answer №1

If you're feeling adventurous, you could experiment with using eval, but proceed with caution:

const out = 'data.option === 1 ? "ABC" : "BCD"'
new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data() {
    return {
      data: {option: 1}
    }
  },
  computed: {
    expression() {
      return eval(JSON.parse(JSON.stringify('this.' + out)))
    }
  }
})
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4d2b2223390d7b6335">[email protected]</a>/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e89e9d8d9c818e91a8dac690">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet">
<div id="app">
  <v-app>
    <v-main>
      <v-container>
        <v-text-field :placeholder="expression"></v-text-field>
      </v-container>
    </v-main>
  </v-app>
</div>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c0b6b5a580f2eeb8">[email protected]</a>/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="04727161706d627d44362a7c">[email protected]</a>/dist/vuetify.js"></script>

Answer №2

If you want to include an expression within a placeholder attribute in Vue, try adding a colon before the property as shown below:

<v-text-field :placeholder="expression"></v-text-field>

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

How can I tap into the page reload event in Nuxt.js?

One challenge I'm facing involves the need to trigger a function each time the user refreshes the page. Typically, this could be achieved by utilizing the created hook in App.vue. However, due to the auto-generated base component in this project, impl ...

Steps to resolve eslint error in cases of using the node: protocol for importing Node.js built-in modules

Can someone guide me on what to include in my .eslintrc file for my specific situation? Link 1 Link 2 If I disable this rule, I encounter the following error: import path from "path"; // ESLint: Prefer `node:path` over `path`.(unicorn ...

Changing the color of the Bootstrap-Vue b-dropdown button when it is open

When it comes to customizing the button color and hover effect, the code below does the job perfectly. However, there seems to be an issue where the button color reverts back to gray when the menu is open and the cursor moves away from the button. How can ...

"Implementation of Google+ button causing the appearance of a horizontal scrollbar

Adding Facebook and Twitter sharing buttons was easy, but now I'm having trouble with Google+. No matter where I place the code on my page (using a Bootstrap grid), it always adds 2-3 pixels on the right side, creating a horizontal scrollbar: <div ...

Toggle between the Angular test/development module and the production module

Currently, I am working on implementing an Angular app. During my e2e tests, I encountered a need to mock some server requests while allowing others to pass through using e2e httpBackend. Vijitta has provided an example of how to utilize the HttpBackend: ...

Creating a component in Vue to showcase Axios, based on a straightforward example from the documentation

I apologize in advance for what may seem like a trivial question, but I assure you that I have put in a considerable amount of effort to solve this problem without success. In my appService.js file, I am making an API call as follows: import axios from &a ...

Empty response returned by Next.js API Routes

I have attempted various methods to retrieve data from a database using MySQL. Here's what I've tried: export default function handler(req, res) { const mysql = require('mysql') const dbConn = mysql.createConnection({ ho ...

What steps do I need to take in order to integrate vue-i18n and vue2 with Storybook's mdx type stories?

After struggling with this issue for a while, I decided to share my solution here in case others are facing the same problem. The setup includes: - "vue": "^2.6.12", - @storybook/vue": "^6.4.19", - "vue-i18n": ...

Deleting database information using Jquery when a div is clicked

I'm looking to create an alert system where users will see a pop-up alert on their screen. However, I am facing a major issue in removing the div completely. I understand that I need to remove it from the database, but I'm struggling with finding ...

Building a personalized version with core-js

I am currently in the process of developing a custom build using core-js. Following the instructions provided, I initiated the following commands: npm i core-js && cd node_modules/core-js && npm i The process seemed to go smoothly. Then, ...

Tips for accessing the parent reference while binding using the .on() method

I needed to attach an event like this $("div").on("click", "li",function() { var div= $(this).parent().parent(); //this is what i'm using //..... }); above the <div> <ul> <li>1</li> <li>e2</l ...

Delete a class that is not identified by the DOM

Currently, I'm developing an interactive map that triggers an overlay image to highlight the selected area. I am trying to dynamically add and remove classes from a div based on the highlighted area. Initially, I attempted using the starts with selec ...

Error in Javascript: Null Object

I have created an upload page with a PHP script for AJAX, but I'm encountering errors in Firebug. Also, the upload percentage is not being returned properly. Currently, I can only do one upload in Firefox and the script doesn't work in Chrome. H ...

Unable to persist session data using Vue and Express

I'm currently working on a project using ExpressJS on the server side and Vue on the frontend. I've been trying to implement session saving, but I'm facing some challenges with the Vue frontend. I haven't been able to find a solution fo ...

Creating images dynamically using JavaScript

I need to insert a logo for each game listed in my table, positioned above the title in the first column. The URLs to the demo logos are found in the "L" column of the source table, where it is also labeled: L: 'Logo', Therefore, I must utilize ...

What is the process for performing the "extract function" refactoring in JavaScript?

Are there any tools for extracting functions in JavaScript similar to the "extract function" refactoring feature available for Java and jQuery developers in Eclipse or Aptana? Or perhaps in another JavaScript/jQuery IDE? ...

Encountering issues with resolving dependencies in webdriverIO

I'm attempting to execute my WebdriverIo Specs using (npm run test-local) and encountering an error even though I have all the necessary dependencies listed in my package.json as shown below: [0-2] Error: Failed to create a session. Error forwardin ...

JavaScript effectively divides multiple child dropdowns with the main dropdown, thanks to Bootstrap innovation

I have implemented a jQuery function to dynamically change multiple child dropdowns based on the selected value of the main dropdown. For reference, you can view the image here. However, I encountered an issue when applying the Bootstrap styles "form-con ...

Is there a way to access the api_token within the controller?

Here is the Vuejs code snippet that I am working with: axios.get('/api/electronic_collection?page='+this.currentPage+'&api_token='+App.apiToken) .then(response => { this.posts = response.data.d ...

Tips for personalizing the Material UI autocomplete drop-down menu

I'm currently working with Material UI v5 beta1 and I've been attempting to customize the Autocomplete component. My goal is to change the Typography color on the options from black to white when an item is selected. However, I'm struggling ...