Is there an appropriate method in Vue/Nuxt for managing and altering component data without using lifecycle hooks?

Scenario: I am dealing with a component that showcases a datatable listing Applications. Upon clicking a row, it triggers the opening of another component with appropriately loaded fields (for new or edit).

The Challenge: The component loads a reference to the data, whether new or existing, which cannot be directly edited due to it being a reference rather than a copy.

Here's a brief breakdown of the code: New() invokes Open(), both functions loading the Component ViewApplication.

Datatable Component

<template>
  <div id="inspire" data-app>
      <v-card>
        <v-banner single-line>
              <v-btn @click="New">New</v-btn>
        </v-banner>
        <v-card>
          <v-layout>
            <v-list-item>
              <v-list-item-content>
                <v-row>
                  <v-col>
                    <v-data-table
                      :items="items"
                      return-object
                      @click:row="Open"
                    >
                      <template #top>
                        <v-dialog v-model="dialog" max-width="600">
                          <ViewApplication
                            :loadedapp="loaded"
                            @reload="Load"
                            @close="close"
                          />

                        </v-dialog>
                      </template>
                    </v-data-table>
                  </v-col>
                </v-row>
              </v-list-item-content>
            </v-list-item>
          </v-layout>
        </v-card>
      </v-card>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
export default {
  data: () => ({
    dialog: false,
    items: this.LoadApplications(),
  }),
  computed: {
    ...mapGetters({
      applications: 'modules/Manage/getApplications',
    }),
  },
  methods: {
    ...mapActions({ LoadApplications: 'modules/Manage/LoadApplication' }),
    Open(item) {
      console.log('Open item: ' + item)
      this.loaded = item
      this.$store.commit('modules/Manage/setApplication', item)
      this.dialog = true
    },
    New() {
      let item = { app_name: '', roles: `[]`, api: '' }
      this.Open(item)
    },

  },
}
</script>

ViewApplication Component

<template>
  <v-card v-if="loadedapp">
    <v-col>
      <v-text-field v-model="app_name" dense label="Application Name" />
      <v-row>
        <v-col col="6">
          <v-text-field
            v-model="role"
            label="Role"
            :append-outer-icon="'mdi-send'"
            @click:append-outer="roles.push(role)"
          />
        </v-col>
        <v-col col="6">
          <v-select
            v-model="roles"
            :items="roles"
            :menu-props="{ maxHeight: '400' }"
            label="Roles"
            multiple
          ></v-select>
        </v-col>
      </v-row>

      <v-text-field v-model="api" dense label="API" />
    </v-col>
    <v-card-actions>Save, Delete</v-card-actions>
  </v-card>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  props: {
    loadedapp: {
      type: Object,
      default: () => {
        return { app_name: '', roles: `[]`, api: '' }
      },
    },
  },
  data() {
    return {
      localapp1: this.getApp,
      localapp2: { ...this.getApp },
      localapp3: this.loadedapp,
      localapp4: { ...this.loadedapp },
      role: '',
      app_name: '',
      roles: [],
      api: '',
    }
  },
  computed: {
    ...mapGetters({
      path: 'modules/Auth/gutCustomerURL',
      getApp: 'modules/Manage/getApp',
    }),
  },
}
</script>

https://i.sstatic.net/7rYFM.png

Answer №1

These resources proved to be very helpful: https://vuex.vuejs.org/guide/forms.html

The solution I implemented:

  props: {
    loadedapp: {
      type: Object,
      default: () => {
        return { app_name: '', roles: `[]`, api: '' }
      },
    },
  },
  data() {
    return {
      role: '',
      app_name: '',
      roles: [],
      api: '',
    }
  },
  watch: {
    loadedapp: {
      immediate: true,
      handler() {
        this.init()
      },
    },
  },
  methods: {
    init() {
      if (this.loadedapp) {
        this.app_name = this.loadedapp.app_name
        this.roles = JSON.parse(this.loadedapp.roles)
        this.api = this.loadedapp.api
      }
    },}

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

Are there any available resources for comparing the performance of JavaScript libraries?

In preparing a presentation for my company, I am outlining the reasons for choosing jQuery as our primary JavaScript / AJAX library. While most of the work is already completed, it would be beneficial to include a comparison with other libraries, particul ...

avoiding less than or greater than symbols in JavaScript

I'm encountering an issue while attempting to escape certain code. Essentially, I need to escape "<" and ">" but have them display as "<" and "> in my #output div. At the moment, they show up as "&lt;" and "&gt;" on the page. This ...

PHP and MySQL form is not being updated with new data

In my database, the fields include: id,name,email_id,address,phone_no,username,password,category,date <?php include_once('connect_to_mysql.php'); if(isset($_POST["submit"])){ $a=mysql_real_escape_string($_POST["name"]); ...

Locate relevant information within the arrays through the process of filtering

For my collection, I am looking to match the operator_name based on date and then further narrow it down by matching shift_name within an array { "_id": "5eb301bc0218ff48b724a486", "date": "2020-07-02T00:00:00.000Z", "shift_wise": [{ "_id": ...

A guide to implementing daily function calls for a week utilizing the @nestjs/scheduler module

Is there a way to schedule a function to run every day for a period of 7 days using Nestjs (@nestjs/scheduler)? @Cron(new Date(Date.now() + (24*60*60*1000) * 7) function() { console.log("This should get called each day during the next 7 days") ...

Validating data with Joi can result in multiple error messages being displayed for a single field

I'm attempting to implement a validation flow using the joi package, which can be found at https://www.npmjs.com/package/joi. 1) First, I want to check if the field category exists. If it doesn't, I should display the error message category requ ...

Using jQuery to Activate Genuine Events

Is it true that jQuery's trigger() only executes event handlers bound with jQuery? I have some modules that utilize native browser event binding. Although the solution from works for me, I'm curious if there is a built-in way in jQuery to handle ...

How can I call the telerik radgrid.databind() function using a JavaScript function?

Currently, I am coding in ASP .NET and have an ASPX page featuring a Telerik RadGrid. I am curious to know if it is feasible to call the RadGrid.DataBind() method from within a JavaScript function? ...

The Vuetify rating system seems to be having trouble displaying

I've integrated the Vuetify rating component into my app (https://vuetifyjs.com/en/components/ratings#ratings), but I'm facing an issue. Despite having Vuetify 1.5.5 installed and working with other components like buttons, the stars in the ratin ...

Conceal the results of echoing json_encode

One dilemma I encountered was passing an array from PHP to JavaScript using json_encode and ajax. The only method that seemed available was to use echo json_encode($var) This approach printed out the contents of $var on the page due to the echo statement ...

Isolating Express.js Requests for Enhanced Security

In my Node.js Express app, multiple users send requests to the server for various actions such as earning points, changing email addresses, and interacting with other users. My server code utilizes several setTimeouts, leading me to question whether diffe ...

Enable and disable subscriptions in real-time to control the amount of cached data and prevent the error message "Uncaught TypeError: Converting circular structure to JSON"

In an attempt to control the cache on the client side, we had the idea of toggling the subscription to a specific Collection on and off by placing the Meteor.subscribe call within a reactive context as recommended in the Meteor documentation - "In addition ...

I am encountering an issue with retrieving API JSON data in NextJS where I am receiving an

Instead of receiving data in my console log, I am seeing undefined. This is my Index.js file (located in the pages folder) import Head from "next/head"; import Link from "next/link"; import axios from "axios"; import Test fro ...

Tips for ensuring synchronous state changes in React

I am working on a currency calculator using react.js I am fetching the latest exchange rates and storing them in state using the getRates function: getRates(currencyShortcut){ fetch('https://api.fixer.io/latest?base='+currencyShortcut) ...

``"Selecting a location upon clicking a marker in the array

I have limited experience with javascript but I am determined to improve my skills. Currently, I am facing a major roadblock in a project that I am working on and urgently require assistance. The project involves creating a map with marked locations from ...

Guide on deleting an item from an object array in AngularJS

I have an array of objects and need to delete a specific object from it: var objectArray = [{"id":"John Doe","label":"John Doe","shape":"image","image":"app/data/img/user_icon.png","color":{"background":"#db630d","border":"#7c3400"},"level":0},{"id":"Java ...

What are the steps to achieve complete test coverage for my Angular login form? Encountering an issue with reading property 'subscribe' of undefined

Recently, I made adjustments to my login component to align more closely with Angular standards. However, upon testing, I encountered errors of this kind: Cannot read property 'subscribe' of undefined After using console.log for debugging pur ...

What is the default state of ng-switch in AngularJS?

I am completely new to using AngularJS and I have a question about setting a default ng-switch state in the following Plunkr. Currently, I can only get it to work when clicking, but ideally the menu should be displayed automatically if the user button is t ...

What is the best way to trigger the opening of a Component upon an onPress event?

One challenge I am facing is implementing a button in my app's Screen that should open a self-made Modal component on the same screen. To achieve this, I have set up a visible state in the screen and created an onPress handler for the button to toggl ...

Issue arises where multiple asynchronous functions cause infinite re-rendering due to the shared loading state

Currently, I am integrating zustand 4.1.5 into my React application. Upon clicking the LogDetails tab, two asynchronous functions with identical loading state settings are triggered simultaneously, leading to an endless rerendering cycle and causing the & ...