Vue - Seamlessly Editing and Creating Content Together

When using Laravel, I am attempting to pass data to a Vue component. Depending on whether the user enters the component through an edit URL or a create URL, we send either an array of data or null. Here is an example of how this process works:

Blade view

 <section id="app">
        <people-form-component :person="{{$person ?? 'null'}}"></people-form-component>
    </section>

This process functions correctly as it displays the data if available, otherwise showing null.

Data array

{"id":1,"created_at":"2021-11-05T19:03:14.000000Z","updated_at":"2021-11-05T19:03:14.000000Z","name":"Eduardo Montoya","lastname":"Jurado","age":83,"dni":"19282246N","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="553f20343b34656715302d34382539307b363a38">[email protected]</a>","id_car":8}

I then proceed to retrieve this prop in my component to show/hide text and call functions accordingly.

People Form Component (Complete code pasted for reference)

  <template>
    <div class="center">
        <div
            class="w-1/2 bg-white rounded p-8 m-6 shadow-md rounded hover:shadow-2xl transition duration-500 ease-in-out">
            <h1 class="block w-full text-center text-gray-800 text-2xl font-bold mb-6">
               {{this.person!=''? 'Update' :'Create'}}</h1>
               ...
</template>

<script>
    export default {
        name: 'PeopleForm',
      ...
    }

</script>

Encountering some errors while working with Vue:

Error 1: When loading the component in the create route, TypeError occurs - "Cannot read properties of null (reading 'name')"

Error 2: When clicking update in the update component, another TypeError is thrown - "Cannot read properties of null (reading 'person')"

As a newcomer to Vue, I am unsure about resolving these basic issues. Can someone provide guidance?

Answer №1

To make your data live empty, you can use the mounted hook to check if it is for updating or adding:

data () {
  return {
    form: {
       name: '',
       lastname: '',
       age: '',
       dni: '',
       email: '',
       id_car: null,
    },
    editing: false
  }
}
mounted() {
  if(this.person) {
    this.form = this.person
    this.editing = true
  }
}

In the template, you can display the corresponding button and trigger the respective event:

<button v-if="editing" @click="update(person.id)"
   class="w-full bg-blue-400 hover:bg-blue-600 transition duration-500 ease-in-out text-white p-3 rounded"
   type="submit">
  Update
</button>
<button v-else" @click="store()"
   class="w-full bg-blue-400 hover:bg-blue-600 transition duration-500 ease-in-out text-white p-3 rounded"
   type="submit">
  Create
</button>

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

Learn the method to conceal rows within a table simply by toggling a button

I need a function that will hide the rows below a row with a header and button, and only reveal them when another row with a header and button is clicked. When one of the +/- buttons is clicked, it should hide or expand all the rows with data content. http ...

I am having difficulty aligning the vertical touch event owl carousel

Here is the link: "jsfiddle.net/nLJ79/". Can you try to find a solution to make the owl carousel vertical? ...

use Vue to submit a form with the latest input data

I have a hidden form that I need to submit with updated values <template> <form ref="form" method="POST" action="https://target.com/post" accept-charset="utf-8"> <input type="hidden" na ...

Import css background-images from a separate local directory that is located outside the root directory of the Next JS

I am facing a challenge with hosting a next.js app within the file structure of a parent website. I need the CSS in the app to use images that are located outside the app's file structure but within the parent website's file structure. Here is a ...

Avoiding an event from spreading in Angular

I am working on a navigation setup that looks like this: <a (click)="onCustomParameters()"> <app-custom-start-card></app-custom-start-card> </a> When the user clicks on the app-custom-start-card, the onCustomParame ...

Invoking a parent controller method from a directive in AngularJS

I have utilized a tree grid plugin from the following link: https://github.com/khan4019/tree-grid-directive and I made some customizations to its template: .directive('treeGrid', [ '$timeout', function($timeout) { return { ...

The Javascript function is designed to function exclusively with onclick events or setTimeout functions

I am currently working on a website that I want to be responsive to the window size. However, I am facing an issue with vertical alignment. I have created a jQuery function to handle this, and it works well for divs with images but not so well for a div wi ...

Discover how to shallow test for the presence of a wrapped component using Jest and Enzyme

Currently, I am in the process of testing a component that dynamically renders another wrapped component based on certain conditions. My testing tools include enzyme and jest, with the root component being rendered using the shallow() method. The main chal ...

Using Nest JS to create two instances of a single provider

While running a test suite, I noticed that there are two instances of the same provider alive - one for the implementation and another for the real implementation. I reached this conclusion because when I tried to replace a method with jest.fn call in my ...

Implementing auto-complete functionality using two keys in Material UI and React

My goal is to enable autocomplete for input when searching with values like title and year. Strangely, the autocomplete feature only works when I search with title. Searching with year does not yield any options. Sample code export default function ComboB ...

How can I efficiently utilize the date picker feature in Angular JS for a smooth user experience?

I am new to AngularJS and attempting to implement a date picker. I initially tried using a basic jQuery UI date picker, but it did not function as expected. Can someone please provide me with some code that demonstrates the simplest way to achieve this in ...

Material Style Minimal - There is a slight space between the text field and the colored line at the bottom

Having a problem with Material Design Lite text field where there is a small gap between the bottom colored line and the gray starting line. Every MDL text field example I try on my page shows the same issue. What could be causing this locally? My frontend ...

Retrieve the offspring with the greatest level of depth within a parental relationship

Consider the following tree structure: -root | | |-child1 | |-innerChild1 | |-innerChild2 | |-child2 I am looking to create a JavaScript function that can determine the depth of an element within the tree. For example: var depth = getInnerDepth( ...

Enhance the axis functionality in c3.js

My goal is to display a user's financial data for the previous week, but sometimes they may not have data for all seven days. When using c3.js, I noticed that it automatically extends the 'endpoint-value' to the end of the axis. Is there a w ...

The Zustand store does not reflect changes when the URL is updated

I have a Zustand store connected to the URL. See the code snippet provided below. import { create } from "zustand"; import { persist, StateStorage, createJSONStorage } from "zustand/middleware"; const pathStorage: StateStorage = { ge ...

Struggling with adding icons to the home screen in a Create React App?

When working with the manifest.json file, various icon sizes are specified as shown in this example: { “src”:”images/icons/apple-icon-57x57.png”, “type”: “image/png”, “sizes”: “57x57”, } In the index.html file, the ...

The Angular service/value is failing to retrieve the updated variable from the $(document).ready() function

Currently, I'm facing an issue with my Angular service/value. It seems to be grabbing the original variable instead of the new one that is supposed to be inside $(document).ready(). Here's the relevant code snippet: var app = angular.module("app ...

Executing changes to Vuex store mutation for array manipulation

File Storage: state: { ... cases: [], ... mutations: { setCases(state, items) { // The 'items' variable contains only the first object in the array ... Component Implementation: // The 'resp' variable ...

Transform jQuery scroll script into vanilla JavaScript

While I am quite familiar with jQuery, I find myself struggling when it comes to using pure JavaScript. Could anyone provide guidance on how I can convert my jQuery code into vanilla JavaScript? Your help is greatly appreciated! Below is the code that I ...

Utilizing operators for whereJsonContains in Laravel

I have a JSON column called "experience" in my database. It contains an array of objects structured like this: [ { ... "years": 1 }, { ... "years": 2 } ] I am looking to retrieve users with experience years greater than or equal t ...