What is the best method for incorporating new data into either the root or a component of Vue 3 when a button is pressed?

One issue I'm facing is the challenge of reactively adding data to either the Vue root or a Vue component. After mounting my Vue app instance using app.mount(), I find it difficult to dynamically add data to the application. As someone new to the framework, I am trying to integrate Vue with vanilla JS. Essentially, I'm wondering if there's an event or object in vanilla JS that can be triggered to insert new data, such as into an array of objects within the Vue app instance.

Answer №1

The most straightforward approach is to integrate Vuex into your Vue 3 application and pass data through the Vuex store.

If you want to create a basic Vue 3 project using vue-cli, you can run the command vue create my-vue-prj

{
  "name": "my-vue-prj",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "core-js": "^3.6.5",
    "vue": "^3.0.0",
    "vuex": "^4.0.0-0"
  },
  "devDependencies": {
    ...((skipped))...
  }
}

Additionally, here is the entry point in src/main.js.

import { createApp } from "vue";
import App from "./App.vue";
import store from "./store";

const app = createApp(App);
app.use(store).mount("#app");

window.vueApp = app;
// Alternatively, you can also expose the store directly
// window.store = store; 
  • Expose the Vue app instance (window.vueApp) for external JavaScript access.

You can access the Vuex store like this.

// external.js
const store = window.vueApp.config.globalProperties.$store
/*
 * You can manipulate data in the Vue app through `store`
 */

Demo

A predefined array is stored in the Vuex store as shown below:

// file : src/store/index.js
import { createStore } from "vuex";

export default createStore({
  state: {
    nums: [0, 1, 2],
  },
  mutations: {
    replaceNum(state, nums) {
      state.nums = nums;
    },
  },
  actions: {},
  modules: {},
});
  • The array nums needs to be displayed in App.vue

You can access the array nums from the component App.vue.

<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <ul>
    <li v-for="(n, index) in $store.state.nums" :key="index">{{ n }}</li>
  </ul>
</template>
  • $store.state.nums represents the array of [0, 1, 2]
  • List items are rendered with values (0, 1, 2)

The array nums can be updated externally using the following script:

// external.js
const store = window.vueApp.config.globalProperties.$store
store.commit('replaceNum', [2, 3, 5, 7, 11]);
  • commit('replaceNum', ...) - This triggers the replaceNum method in mutations, updating the nums array and refreshing the contents as well.

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

An easy way to incorporate a fade-in effect for every word in a text

I am trying to make the text "Eat. Sleep. Repeat." slide up and fade in one word at a time. I have experimented with various methods like anime.js, keyframes, and adding css classes, but so far none of them have worked for me. Here is the code I currently ...

Optimizing image centering in Next JS as screen size expands

I've been struggling to work with NextJS's Image component. My goal is to set up a banner image that only covers a specific amount of space on the screen, regardless of screen size. I have managed to achieve this by using max-height: 30vh and ov ...

"Encountering an issue with AJAX file upload displaying an error message for

Before I showcase my code, allow me to explain my objective. My goal is to create a page that updates a user's details in the database using AJAX. Initially, I successfully achieved this task. Subsequently, I wanted to enhance the functionality by inc ...

Flashing images with jQuery Flickrush - Encasing the image within <li> tags

I have a div with an unordered list inside: <div id="flickr"> <ul></ul> </div> Currently, I am utilizing a plugin found at this link. To make it functional, I've included the following Javascript code: $(function() { $( ...

Is there a way to prevent the "undefined" message from displaying in the console when this code is run?

Help needed! Can someone assist me in resolving the issue where the word 'undefined' is being displayed in the console? I'm a beginner in programming and struggling with this. Here's what I'm currently seeing: You are not getti ...

Creating the document.ready function in Angular2 with JQuery

I am seeking assistance to modify the JQuery function so that it can run without the requirement of a button click. Currently, the function only executes when a button is clicked. Code declare var jQuery: any; @Component({ selector: 'home-component ...

Unable to logout with ExpressJS passport-local

After pasting the passport-local app into my own, I noticed something interesting: I managed to successfully log in users, but for some reason, I can't seem to get them logged out. app.get('/logout', function(req, res){ req.logout(); r ...

Unable to perform dynamic query with $in operator in Mongoose find method

I am currently utilizing Node.js along with Mongoose version 5+ to create a dynamic query in my database. The variable filterField represents the field name, while filterValues is an array. Here is an example of how my code looks: if (req.currentUser.acti ...

Switch out the URL in npm's build process

While developing, I am using a mock REST service but for the public release, I intend to switch to a real backend. Is there a method to update the endpoint URL during the npm build process? ...

Struggling to pass two objects as props and have them be equated to one another

I have a scenario where I am passing a worker object as a prop to the view.vue field. In the mounted method of the component, I am trying to assign this worker object to the manager object. However, when I use the assignment `this.manager = this.worker`, i ...

Running a JavaScript file with Node.js

My node.js script is named Index.js and I also have another file called bot.js. How can I execute the bot.js file using Node.js? var fs = require('fs'); const commandFiles = fs.readdirSync('./users/commands').filter(file => file.e ...

Can an older style class be inherited from an ECMAScript 6 class in JavaScript?

When I run the code below on Node.js version 4.2.1: 'use strict'; var util = require('util'); class MyClass { constructor(name) { this.name = name; } } function MyDerived() { MyClass.call(this, 'MyDerived'); } ...

What could be the reason for the styled-jsx not applying the keyframe animation?

When attempting to add the animation separately without any conditions, the transition fails to be applied. Changing the quotation marks to backticks for the animation property also did not work. Is there a way to apply both the animation when clicked is ...

Can someone help me figure out where I'm going wrong with the JS ternary conditional operator

Looking to improve my JavaScript logic skills as a beginner. Appreciate any tips or feedback on the function and not just this specific question. I'm curious why the code outputs --> [3,5] function divisors(integer) { let divisors = [] for (le ...

Problem with jQuery form button in dynamic table detecting rows after the first

I am currently working on a file that generates a dynamic table based on the records in a database. Each row in the table has a button to delete that particular row. The code I have written works perfectly for the first row, but it fails to detect the row ...

JavaScript/jQuery: Retrieve the correct header for every element

Looking at the given HTML structure (which is just an example and may not be entirely logical): <div id="wrapper"> <h3>First Heading</h3> <div class="row"><div class="col-12"><p class=& ...

Guide to choosing and unchoosing a div / button using angularJs

I am attempting to create a functionality where items are displayed in a div instead of a list. When an item is clicked, the background color of the div changes and the item is added to a column. Clicking on the item again will revert it back to its origin ...

Discovering additional element information while utilizing the 'Sortable' feature

My Current Objective: In my setup, I have a 'calendar' comprising 5 columns, each column containing 5 separate divs known as timeslots. The main purpose here is to show appointments in these specific timeslots and utilize JQuery's Sortable ...

Avoid duplicating the use of the same controller in a page to prevent mirroring each other

I have implemented MVC partial controls on my page twice to handle search functionality. Each partial control has its own controller for searching, resulting in my page having two controllers with the same name. <div ng-app="app" ng-controller="MainCon ...

The Gridsome website deployed on Netlify seems to be experiencing some issues. When clicking on links, the pages are not loading properly despite

After deploying my site on Netlify, I encountered an issue where the URL updates when clicking on links on the landing page, but the content does not show unless the page is refreshed. Interestingly, this issue does not occur on my local development server ...