When attempting to reference from a variable, you may encounter an error stating that setAttribute

In my VueJS project, I am facing an issue with dynamically adding the width attribute to an inline SVG code stored in a variable called icon. Despite having the correct SVG icon code in the variable, the setAttribute method is not working as expected and throwing errors. I'm unsure of what I might be overlooking.

Here's a snippet from the Vue template where I intend to display the inline SVG code:

<code v-text="appendDimension"></code>

This is how it looks inside the single Vue component:

export default {
  name: "App",
  data() {
    return {
      dimension: 50,
      icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path d="M11 9h4v2h-4v4H9v-4H5V9h4V5h2v4zm-1 11a10 10 0 110-20 10 10 0 010 20zm0-2a8 8 0 100-16 8 8 0 000 16z"/></svg>'
    }
  },
  computed: {
    appendDimension() {
      return this.icon.setAttribute("width", this.dimension);
    }
  }
};

I have set up a demonstration project on CodeSandbox for you to reproduce the issue. Your assistance would be greatly appreciated.

Answer №1

To modify the value of this.icon dynamically, you can update the string before returning it in your computed method. Here is an example of how your computed method could be structured:

computed: {
    appendDimension() {   
      return this.icon.replace("<svg ", "<svg width='" + this.dimension + "' ");
    }
  }

Don't forget to change

<code v-text="appendDimension"></code>
to
<code v-html="appendDimension"></code>
because you want to render the HTML and not just display the string itself. Just a friendly suggestion 😉

Answer №2

Within this particular function, the variable this.icon holds the initial value set in the .data() method as a string, not an actual <svg> element.

Furthermore, using .setAttribute() as the return value within a return statement is illogical since it always results in undefined.

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

Implementing an active class in Vue.js for the router-link component

I am facing an issue with my sidebar item becoming inactive when I click on a sublink inside a component. How can I prevent the active class from switching off? Here is my sidebar: <router-link to='/sub/success_tools_subscriptions' ...

As you scroll, a box blocks off half of the screen

Hey everyone, I could really use your assistance! I'm working on developing a javascript code and here is the idea - if anyone can contribute to it. It's like a social media platform where users enter the site and the is_user_logged_in parameter ...

What is the proper way to include an attribute to every individual object within an array?

Here is the structure of my array: "taxDetails": [ { "taxType": "Flat Service Charge", "taxAmount": 0 }, { "taxTypeId": "1", "taxType": "Service Tax", "validFrm": "2016-01-18", "validTo": "2020-02-27", "taxPrctgSbt": 200, "taxPrctg": 14.5, ...

The issue arises when attempting to render an SVG with JavaScript embedded inside using the img, object, or

Issue with the title ... please follow these steps: (view codes below) Create an svg + open it separately (name it keysaway.svg) Create html + open it individually When you observe, the svg displays a simple up and down animation but fails to work when l ...

Vue - Struggling to invoke sweetalert2 within a method

I'm encountering an issue with launching sweetalert within a Vue method. When I directly call the sweetalert in the script, it works fine. However, when I try to launch the sweetalert upon clicking a button, nothing happens (no errors in the console). ...

Exploring Vue: Utilizing Custom Components for Array Input Bindings

Vue's v-bind syntax allows for binding multiple checkboxes with different value attributes to the same array, which stores the values of all checked checkboxes. Check out this example: https://vuejs.org/guide/essentials/forms.html#checkbox But can we ...

Vue3: Implementing function overrides using the Composition API

Consider a composable function as shown below: // composable/useShareComp.ts export function useShareComp() { const toto = "hey"; const tata = ref(0); function utilMethod() { console.log("Util Méthod !!"); } function mai ...

UI Router: Easily navigate to a specific route by entering the URL directly

I encountered what I thought would be a common issue, but my search turned up empty. I have two states - one accessed at /route and the other at /route/{name}. Everything functions properly when I navigate to the second route using ui-sref, however, if I r ...

React Material UI Select component is failing to recognize scrolling event

Having some difficulty understanding how to detect a scroll event with a Select component using Material-UI. The Select has MenuProps={...}, and I want to listen for the scroll event inside it. I've tried putting onScroll within MenuProps={...}, but ...

Develop a nodejs script to make a request using a curl or similar method

Can anyone help me figure out how to replicate the functionality of this OpenSSL command using Node.js or curl? The command is: openssl s_client api-prd.koerich.com.br:443 2> / dev / null | openssl x509 -noout -dates. I have been unsuccessful in my at ...

Share a status on Facebook with an earlier date

How to Modify Facebook Post Date using Graph API facebook facebook-graph-api I am able to publish on my wall using the Graph API. By utilizing FB nod and graph, I now need to post on Facebook with a date from the past Afterwards, I can adjust the date man ...

Having trouble extracting a JSON object from a POST request in Express v4 with the help of body-parser?

Currently, I am delving into the world of server-side code and learning about Node.js and Express. However, I am facing some challenges when it comes to receiving and parsing a JSON object sent from a POST request. Despite checking various resources (linke ...

hiding elements yet passing down

Despite disabling the style sheet, a dynamically created form is displaying strangely. This form will show or hide various details based on selected options. For instance, many of the elements are generated with C#.net... formOutput += "<div class=&bs ...

Utilize Twilio to forward messages to a different phone number

I am seeking a solution to automatically forward incoming messages from one Twilio number to another, based on the original sender's number. For example: If I receive a message on my Twilio number "+14444444444" from '+15555555555', I want ...

Optimal Placement of CSS and index.html Files in ReactJS with Redux

Currently, my setup for the index.html file looks like this: <!doctype html> <html class="no-js" lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Pra ...

Designing unique variations using Material UI

I am currently exploring the creation of custom variants for the Button component in Material UI. To start off, I am developing a customized component based on the Button component with specific styles: // CTA.js import { makeStyles } from "@materia ...

JavaScript's ability to call object properties at multiple levels allows for complex data

My approach involves using mongodb in conjunction with ajax calls for data retrieval. However, I have encountered an issue where the properties needed to generate HTML from JavaScript objects are sometimes missing. Consider this ajax call: $.ajax({ ...

Tips for selectively executing a script based on whether the DIV is within the viewport

I have a created a script as shown below: jQuery(function($) { $('.count').countTo({ from: 0, to: '400', speed: '3000', refreshInterval: 50, onComplete: func ...

Error occurred in AngularJS service due to incorrect data type

Looking to store the URL of a query in an AngularJS service like this: var mortgageloanService = angular.module('loanstreetIpadAppApp', []); mortgageloanService.factory('updateTable', function($http) { return { getParams: fun ...

React is unable to identify the `InputProps` prop when applied to a DOM element

Caution: React is not able to identify the InputProps property on a DOM element. If you intend for it to be displayed in the DOM as a custom attribute, spell it in lowercase as inputprops. If you accidentally passed it from a parent component, remove it fr ...