What is the best way to change a Vue prop using an external JavaScript function?

In my current project, I am developing a website utilizing PHP templates and jQuery. One of the features includes a table built with Vue:

let vuetablecomponent= new Vue({
  components: { ManualTable },
}).$mount('[data-vue-app=manualtable]');

I am looking for a way to control the state of the Vue table externally. Right now, I am directly changing the props using JavaScript, like so:

vuetablecomponent.$children[0].aprop = 'propvalue'

Vue has warned me about the direct manipulation of props:

Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value.

Although technically I do not see it as an issue since the parent component is not a Vue component, and I want the value to be updated if the page is re-rendered by PHP, I am curious if there is a more elegant solution for this scenario.

Answer №1

How can you display the component and pass a prop to it upon initial render?

Regardless of whether you are using PHP templates or plain HTML, you need to initialize the Vue app in some way so that the browser can load a Vue component properly.

You can follow either of these methods:

Method A (using the render method):

--- init-app.js --
new Vue({
  el: '#app',
  render: h => h(App)
})


-- App.vue --
<template>
  <MyTableComponent :a-prop="tableProp" />
</template>

<script>
export default {
  data() {
    return {
      tableProp: "123-abc",
    };
  },
}
</script>

If you are using this method, simply create a reference to the component like this:

mounted() {
  window.__APP__ = this
}

and then update the tableProp wherever needed by using

window.__APP__.tableProp = "new-value"

Method B (using HTML content as the template):

--- index.php ---
<?php
<html>
  <body>
    <div id="app">
      <MyTableComponent :a-prop="tableProp"></MyTableComponent>
    </div>
  </body>
</html>
?>
new Vue({
  el: "#app",
  component: {
    MyTableComponent,
  },
  data: {
    tableProp: "123-abc",
  }
})

If this is the method you are using, create a reference to the app like this:

window.__APP__ = new Vue({})

Ensure that Vue is loaded before your script that updates this prop so that the variable is properly set.

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

What are the steps for releasing a Next.js app as an npm package?

Currently, my web application is developed using Next.js. I am interested in distributing it as an npm package for others to utilize in their projects. Despite my efforts to search and seek assistance through Google, I have not come across any valuable ins ...

The data in the partial view is not being properly shown by using ng-repeat

Welcome to my code snippets! var app = angular.module("AppModule", ["ngRoute"]); app.factory("DataSharing", function () { return { value: 0 } }); // Setting up Routing app.conf ...

Ensuring consistency of variables across multiple tabs using Vue.js

In my vuejs front-end, a menu is displayed only if the user is logged in. When I log out, the variable isLogged is updated to false, causing the menu to hide. If I have multiple tabs open with the frontend (all already logged in) and I logout from one tab ...

Tips for effectively splitting arrays nested within an array using JavaScript

Here is an example of slicing an array to generate a new one: var array= [ [1,"dataA","dataB","dataC","dataD"...], [2,"dataA","dataB","dataC","dataD"...], [3,"dataA","dataB","dataC","dataD"...], [4,"dataA","dataB","dataC","dataD"...]... ...

To dismiss a popup on a map, simply click on any area outside the map

Whenever I interact with a map similar to Google Maps by clicking on various points, a dynamically generated popup appears. However, I am facing an issue where I want to close this popup when clicking outside the map area. Currently, the code I have writte ...

Enhance your Django website with the powerful jQuery Datatables plugin

I am relatively new to using django and I have integrated jquery datatable plugins into my django application. Currently, these datatables are functioning well with small datasets retrieved from my view. However, I am facing challenges when trying to displ ...

Ways to verify if information is being added to a JSON file or not

JSON Here is the JSON structure where I am adding data with a button click event. var myData = { "info" : [] }; JavaScript Function I have written this function to add data to the JSON object: myData.info.push({ "Name" :name, ...

How can I notify an error in CoffeeScript/JavaScript when a parameter is not provided?

Initially, I believed that my code was clever for accomplishing this task: someFunction = (arg1, arg2, arg3) -> if _.some(arguments, (a) -> a is undefined) throw new Error "undefined parameter" My goal was to throw an error if any of the para ...

Simplest method for storing small amounts of data

As a beginner in coding, I may be asking a question that seems obvious to some. I successfully created a web app using html/JavaScript that collects user input and transforms it into a variable of my interest. The data I want to extract is stored in an arr ...

How to retrieve an element by its class using JavaScript and Jquery while implementing a

I am working on creating a quiz example using Jquery, but I am facing some challenges when trying to manipulate CSS classes with hover in Jquery. .right{ background-color: white; } .wrong { background-color: white; } .right:hover { background-color ...

What is the best way to retrieve the value of a select tag in Vue JS?

Delving into Vue JS has presented me with a challenge. I'm aiming to retrieve the value of the selected option. But unfortunately, I'm stuck. Despite my efforts to scour Google for answers, I have come up empty-handed. Below is a snippet of m ...

Positioning Multi-level Drop Down Div in Javascript - How to do it efficiently?

I'm currently working on a horizontal menu using CSS and JavaScript with multiple levels. I've implemented a toggle function to show the submenu container, but it's causing the links below it to be pushed down. Is there a way to make the dis ...

Switch the cursor to display the magnifying glass icon for zooming in and out

I am curious about how to modify the cursor shape to display a zoom in and zoom out symbol. Changing the cursor to indicate busy or wait status is something I am familiar with, document.manual_production.style.cursor='wait'; However, I am unsu ...

Troubleshooting: WordPress failing to launch Bootstrap Modal

I recently transformed my PHP website into a WordPress theme, but unfortunately, I am facing an issue with my Bootstrap modal not opening in WordPress. ***Header.php*** <a id="modal_trigger" href="#modal" class="sign-in-up"><i class="fa fa-user ...

Download a file on button click using JavaScript with data extracted from the DOM

I am looking to create a download feature where a user can click a button on the webpage, triggering a JavaScript method to capture the contents of a DOM element and prompt the user for a download. After successfully capturing the DOM element in a JavaScr ...

Experience the power of Vue.js combined with Axios for easy data fetching and manipulation with JSON

Apologies for the repeated posting, but I have exhausted all solutions found online to no avail. This issue seems to be quite common, yet I am unable to resolve it. After dedicating an entire day to solving it, I am throwing in the towel. It must be a mino ...

Reacting to URL Changes but Failing to Load the Requested Page

Welcome to my App Component import React, { useEffect } from 'react'; import './App.css'; import Navbar from './components/layout/Navbar'; import Landing from './components/layout/Landing'; import { BrowserRouter as ...

Why is my Vue element being titled incorrectly by default?

I recently converted a Vue component to class syntax, following the same process I used for three other components in my project. However, after reducing the code to just the problematic section, I encountered this issue: <template> <v-container ...

Transmit an array using a GET Request

I am currently working on a project where I need to make a GET request from JavaScript to Python and pass a 2D array. Here is an example of the array: [["one", "two"],["foo", "bar"]] However, I am facing issues with passing this array correctly. In my Ja ...

Having trouble running classes using Maven test with the Testng.xml file in the terminal, however, it runs smoothly in Eclipse

While I have been successful in running my solution through the testng suit in the Eclipse console, I am facing difficulties executing the testng.xml file via Maven integrated with Sauce Labs in the terminal. Output received on the terminal: ------------ ...