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

Using HTML and CSS to generate an alpha mask on top of an image

I am currently working on a website and I am looking to create an effect where an image is masked by an overlay. The goal is to achieve a "fade out" effect, without any actual animation, but rather make it appear as if the image is gradually fading into th ...

Unlocking the secrets of integrating Vuex store with JavaScript/TypeScript modules: A comprehensive guide

I am working on a vue application and I have a query. How can I access the store from javascript/typescript modules files using import/export? For example, if I create an auth-module that exports state, actions, mutations: export const auth = { namesp ...

What are the steps to integrate node-inspector with `npm start` in my application?

Currently, I am utilizing npm start to kickstart my MEAN stack application. However, I am interested in using the node-inspector to debug some Mongoose aspects. I am aware that the node inspector can be initiated with node-inspector, but I am unsure of wha ...

Is there a way to switch the default text mode from plain to code, such as HTML?

Is there a way to switch from plain text mode to code mode, specifically HTML, in Sublime? I often find the need to change the mode from plain text to HTML when working on projects. ...

Is there a way to specify both a fixed width and a custom resizable length for a Spring <form:textarea /> element?

Despite extensive research, I have yet to find an answer to my specific problem. Within a model window, I have a textarea element: <div class="form-group"> <label for="groupDescription" class="col-sm-2 control-label"> Descripti ...

Determine the maximum size of a specified number of square divs that can fit within responsive parent divs

I am working on creating a grid of square divs inside a container with variable height and width. The number of square div's is predetermined. All square divs will have images with the same dimensions (similar to the example). They should align left ...

What is the definition of reusable components within the context of Angular, React, and Vue?

I've been hearing a lot about reusable components. What does this actually mean? For instance, if I want to showcase basic user information like ID, name, age, etc. Does it imply that the component is "plug and play," where you simply write the sele ...

Retrieve the property of an object from within an array

I am dealing with an array structure like this: const arr = [{ name: 'One', id: 1 }, { name: 'Two', id: 2 } ]; My goal is to extract and return the name of the object if its id matches a certain value. After exp ...

Pseudo-element fails to display in React when applied to a paragraph tag, even with display block property set

I am experiencing an issue where the pseudo element ::after is not appearing in my browser. I am currently working with React.js and Material UI's makeStyles. Here is the code snippet causing the problem: modalTitle: { borderBottom: '2px sol ...

Next.js App encounters a missing API route (The requested page is not found)

I have been working on a Next.js app and I created an api route for sending emails. Everything is functioning properly in my development environment. However, after deploying to production, I encountered a 404 error with the message "The page could not b ...

Incorporate attributes into object properties in a dynamic manner

Currently, I am experimenting with bootstrap-multiselect and my goal is to incorporate data attributes into the dataprovider method. Existing Data Structure: var options = [ {label: 'Option 1', title: 'Option 1', value: ' ...

Personalized style for text overflow property

The application is created using Angular. Within a component, we have a div containing some text: <div>abcdefghijklmnop<div> Depending on the screen size, the text should either be fully displayed or clipped. I discovered the property 'te ...

Sending a jQuery form to a node.js connect-form involves passing the form data through AJAX to

On the server side, I have implemented the following function as an expressjs middleware: function objCreation(req, res, next){ req.form.complete(function(err, fields, files){ if (err) { next(err); } else { // Set params in request ...

Styling the content within Template Strings is not supported by VSCode

Recently, I've noticed that there are two scenarios in which my VSCode doesn't properly style the content within my template strings. One is when I'm writing CSS in a JavaScript file, and the other is when I'm fetching data from GraphQL ...

Ways to alter and remove ArrayList arrangement

I am new, so please excuse all the questions. Could you kindly explain to me? <ul id="example-1"> <li v-for="item in items"> {{ item.message }} <v-btn>up</v-btn> <v-btn>down</v-btn> ...

Tips for showing data associated with the chosen option from a dropdown list in Angular.js fetched from an API

My goal is to automatically display the coordinator's name based on the selection in a dropdown list populated with data from an API. The dropdown options are the email addresses from the JSON data below, and upon selecting a login ID, the correspondi ...

The textarea fails to maintain the correct size when set to display none

Adjusting Textarea Style overflow:hidden; outline: none; border: none; width: 100%; resize: inherit; When running a foreach loop, notes are retrieved (newRecord) and the text and id of the original notes are extracted from them. To keep it ...

The evaluation of CKEDITOR's execution code

Every time I input my content into CKEDITOR, I receive the following error: "Unexpected token < " This is the code I am using: eval('CKEDITOR.instances.'+ckeditorID+'.insertHtml('+text+')'); The content of variable text ...

Experiencing a problem with XAMPP? Changes made to the code are not reflected after saving

Recently, I've encountered a strange issue with my XAMPP test server while working on a game project. Everything was running smoothly until I noticed that when I make changes to certain files in Notepad++ and save them, the updates are not being refle ...

The `XMLHttpRequest.prototype.open` function does not capture every single HTTP request visible in the chrome-dev-tools

While utilizing a third-party embedded code that initiates HTTP requests with a request header origin different from my own, I encountered an issue. Despite attempting to intercept these HTTP requests using XMLHttpRequest, they do not get intercepted. This ...