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

What causes the low Performance score of a default NextJS Application with no content?

Just started experimenting with my initial Next.js project. Upon generating a new project using create-next-app, I decided to test its performance with the web application 'Lighthouse'. Surprisingly, although most other metrics scored above 90, ...

What is the best way to organize class usage within other classes to prevent circular dependencies?

The engine class presented below utilizes two renderer classes that extend a base renderer class: import {RendererOne} from "./renderer-one"; import {RendererTwo} from "./renderer-two"; export class Engine { coordinates: number; randomProperty: ...

Double submission issue with Angular form (multiple ajax requests)

My controller seems to be causing a form submission issue in AngularJS where the form is being submitted twice via a get request. Upon checking my database and the console network tab, I noticed that two submissions are logged, with the first submission sh ...

Exploring JavaScript Unit Testing: Essential dependencies for testing with Karma, jasmine, and bootstrap

After creating an application using AngularJS and additional tools based on bootstrap, I am now facing the challenge of testing everything. However, there seems to be a problem with Karma and Jasmine as an exception is thrown when running the tests. The i ...

v-autocomplete no selected option

Within my Vue.js 2 and Vuetify component, I am receiving the following data : [ { "anio": 2022, "__typename": "Grupo" }, { "anio": 2020, "__typename": "Grupo" }, { "anio": 2018, "__ ...

Using various jQuery autocomplete features on a single webpage

UPDATE I have observed that the dropdown elements following the initial one are not being populated correctly. .data( 'ui-autocomplete' )._renderItem = function( ul, item ) { return $( "<li></li>" ) .data( "i ...

Transforming a base64 encoded string into a byte array

I have implemented a form where users can upload images to the page using an <input id = "fileLoader" type = "file" />. With JavaScript, I convert these uploaded images to base64 and send them to the server. On the server side, I need to decode this ...

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? ...

Exploring the integration of asyncData with Vuex Store for seamless outsourcing

I am in the process of fetching data from firebase that I would like to be server-side rendered for SEO indexing using asyncData on a page. asyncData() { return firebase.firestore().collection('Programms').get().then((querySnapshot) => { ...

"Apply a class to a span element using the onClick event handler in JavaScript

After tirelessly searching for a solution, I came across some answers that didn't quite fit my needs. I have multiple <span id="same-id-for-all-spans"></span> elements, each containing an <img> element. Now, I want to create a print ...

The callback function in AngularJS filters

I'm currently using an AngularJS filter to sort through a list of items. Here is the Jade markup I am using: li(ng-repeat="parcel in parcels | filter : filterActiveAreaParcels") After the filter function runs and the elements are displayed in the DO ...

Exploring Array Iteration and Incrementing with Easing Techniques

I am currently working on a function that involves iterating over an array and incrementing the values by varying amounts. The challenge is to decrease these incremental amounts as the values in the array get larger. Let's consider the following exam ...

Unable to display the column data labels in Highcharts due to the incorrect formatting being presented

I'm having trouble displaying the datetime format at the top of a column in my chart. Although the tooltip shows the correct data when hovering over the columns, the labels are not formatted properly. Received output - 86340000 Expected output - 23: ...

The jQuery validation feature is failing to function properly within a bootstrap modal

I'm facing an issue with the jQuery validation plugin in my express app sign-up form that uses Bootstrap for the front-end. Despite setting rules and messages for name, email, and phone number fields, the validation is not functioning correctly. Below ...

Choose a JavaScript function by clicking on the HTML text

As a beginner in the world of coding, I have been diving into JavaScript, HTML, and CSS. Inspired by fictional supercomputers like the Batcomputer and Jarvis, I've challenged myself to create my own personal assistant to manage tasks, games, programs, ...

I am struggling to showcase the values of character names stored within an array

I am currently developing a Library Express App and utilizing fake data to easily showcase the values on the screen. const PopularBooks = [ { id: 1, title: "Harry Potter", characters: [ { id: 1, name: "Har ...

Vue error: Issue with rendering - "Post text does not have a toLowerCase function"

I encountered an error while attempting to filter my array using a searchbar input. The search operation is performed as a computed property. <div class="post" @click="getData(post.header,post.text)" v-for="(post) in searchList" v-bind:ite ...

The functionality of the Dynamic TailwindCSS class is experiencing difficulties in functioning correctly

After reviewing my code snippet: <template> <section class="bg-gradient-to-br h-40" :class=" 'from-palettes-' + palette + '-primary to-palates-' + palette + '-secondary& ...

Iterate over an array in JavaScript and include the elements as parameters in an SQL query

Can I set an SQL string to a variable in JavaScript and populate part of it by looping through an array? Here is the initial SQL: var tag = ["fun", "beach", "sun"]; var sql = "SELECT * FROM myTable " +"WHERE id > 5" //... // L ...

Unable to assign headers once they have already been sent to the recipient - a Node.js error

Encountering an error message stating "Cannot set headers after they are sent to the client." I've researched and it seems like multiple callbacks may be causing this issue. However, I'm struggling to find a solution. Any assistance in resolving ...