What is the best way to assign a value to a Vue component instance?

I am trying to send a value from my web component to the Vue instance and then use it in a Rails html.erb file. The element where I am mounting the Vue instance is shown below:

    <div id="app" :purchaseId="1">

However, I have been unsuccessful in passing the value to the Vue instance. The Vue instance is defined in main.js as follows:

export default new Vue({
  store,
  vuetify,
  render: h => h(App),
  data: {
    purchaseId: null
  },
  methods: {
    setJson(payload) {
      console.log("payload", payload);
      this.purchaseId = payload;
    }
  }
}).$mount("#app");

My ultimate goal is to pass this value to a child component. Can anyone provide guidance on how to achieve this?

Answer â„–1

It appears that binding the attribute to the method rather than the data property is the preferred approach, with the data coming from Rails being passed as a parameter: First solution:

  <div id="app" :purchaseId="setJson(1)">

or

  <div id="app" :purchaseId="setJson(<%= purchaseId %>)">

export default new Vue({
  store,
  vuetify,
  render: h => h(App),
  data: {
    purchaseId: null
  },
  methods: {
    setJson(payload) {
      console.log("payload", payload);
      this.purchaseId = payload;
    }
  }
}).$mount("#app");

Second solution :

Another option is to utilize JavaScript to retrieve the value using $refs and the getAttribute method:

<div id="app" ref="app" purchaseId="<%= purchaseId %>">
export default new Vue({
  store,
  vuetify,
  render: h => h(App),
  data: {
    purchaseId: null
  },
  methods: {
    setJson(payload) {
      console.log("payload", payload);
      this.purchaseId = payload;
    }
  },
 mounted(){
    let payload=this.$refs.app.getAttribute('purchaseId');
    this.purchaseId = payload;

  }
}).$mount("#app");

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

Is it possible to substitute the variables with the function name?

Is there a way to duplicate the variable name? Take a look at the example below (note the name a1) $(document).ready(function() { name = "a1"; // This is "NAME" as a1 }) function name() { // USING "NAME" $("#test" + name).keydown(function(a) ...

Retrieve the width of an element once the browser has finalized its dimensions

I am facing an issue with centering a pop-up box perfectly within the window using CSS properties. The code for the pop-up box styling is as follows: #pop_up { position: fixed; display: inline-block; border: 2px solid green; box-shadow: 0p ...

`Common issues when running NPM INSTALL in a Vue project`

I purchased a template and tried to install it on my PC, but I encountered an issue with the dependencies. When I run the NPM INSTALL command, I receive an error related to Python 2. About a year ago, I installed the template without any problems. However ...

Using Jquery for Animation: Tips on Revealing Text After Changing Element Color or Styles

Hey everyone, I ran into a bit of trouble while working with jQuery and trying out some animations. My goal was to make a textbox appear and display text when a button is highlighted, similar to a gallery setup. However, I managed to get halfway through th ...

Saving numerous files with Promises

There is a Node URL (created using Express) that enables users to download static images of addresses. The calling application sends a request to the /download URL with multiple addresses in JSON format. The download service then calls Google Maps to save ...

Determining the selected number option with jquery

In my HTML page, I have a set of select menus as shown below: <label>Product Details</label> <select id="PD"> <xsl:for-each select="PRODUCT_DETAILS"> <option value="{DATA0}"><xsl:value-of selec ...

Module lazily loaded fails to load in Internet Explorer 11

Encountering an issue in my Angular 7 application where two modules, txxxxx module and configuration module, are lazy loaded from the App Routing Module. The problem arises when attempting to navigate to the configuration module, as it throws an error stat ...

Having trouble displaying data on the front end with Node.js and hbs due to issues with Json parsing

Server side: app.get("/basket", (req, res) => { fs.readFile("products.json", (err, data) => { if (err) { res.status(500).end() } else { res.render("basket", {products: JSON.parse(data)}) } ...

using props as arguments for graphql mutation in react applications

Here is the structure of my code: interface MutationProps{ username: any, Mutation: any } const UseCustomMutation: React.FC<MutationProps> = (props: MutationProps) => { const [myFunction, {data, error}] = useMutation(props.Mutati ...

Tips for accessing files following the transmission of a post request within the req.body

Encountering a problem where image uploads to an s3 bucket are not successful. The error message received is: API resolved without sending a response for /api/upload/uploadPhoto, this may result in stalled requests. The front end includes an input that ca ...

Is it possible to derive the language code without using the Common Locale Data Repository from a rough Unicode text

I am currently developing a dictionary application. One of the features I am working on involves identifying the language of a Unicode character when entered by a user. For example: 字 - would return ['zh', 'ja', 'ko'] ا٠...

I noticed that my API call is being executed twice within the router function

In my NextJs project, I am utilizing Express for routing. I have implemented a router with a dynamic :id parameter which triggers an axios call to check the ID in the database. However, I am facing an issue where the API is being called twice when the :id ...

Guide to attaching and displaying an image on a Three.js map

Currently, I have a 3D map loaded with three.js that includes mouse interaction. I've managed to place an image on the map using absolute positioning, but unfortunately, as I move the map around, the image stays stationary. Does anyone know how I can ...

Develop a new entity utilizing Array in Javascript

let DaysArray: any = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"] I am looking to transform the above array into an Object structure as shown below: let DaysObject: any = { time: { headerName: "" }, m ...

Exploring modifications in axis for Google charts timeline

Can anyone help me figure out how to set my Google Timeline chart to always display 24 hours on the x-axis? Currently, it automatically changes based on the earliest and latest points, but I want it to consistently show all 24 hours. For example: ...

Implement lazy loading in VueJS when using the v-for directive on components

I am trying to optimize the loading speed of my website. Currently, all the projects are loaded on the initial page load which is causing a delay. I want to implement lazy loading for these components, specifically for a component called project-card. Howe ...

JavaScript: Reorder an array to alternate between largest and smallest elements, starting with the largest

When working with an array of integers that need to be sorted in a specific order, such as: [1, -1, -3, 9, -2, -5, 4, 8,] We must rearrange them so that the largest number is followed by the smallest number, then the second largest number followed by the ...

An issue arose during the process of bringing a vue-cli application into another repository

After developing a component library using vue-cli 3, I incorporated it into another repository to make use of the components. Unfortunately, I am now encountering the following error: Uncaught Error: Module build failed: Error: Couldn't locate prese ...

Utilizing dropzone.js in a Vue application to trigger a function with the name of the uploaded image

I'm struggling to make this work as I want to, but I do have a functional dropzone setup in my Vue project. While I can upload images and trigger functions within the dropzone, I'm looking to directly call a function from the HTML form to send t ...

How to centrally align Vuetify's dropdown menu with the button

Below is a drop-down menu with two rows of v-list items: <v-menu class="dropdown" open-on-hover offset-y > <template v-slot:activator="{ on, attrs }"> <v-btn class="rounded-xl green darken-3 text-ca ...