1

I have a vue form and I am trying gather the data into an object, But when one object element is empty then Id want that field to be destroy'd.

this is my input field:

 <input v-model="fields.title" >

my data:

 data() {
        return {
            fields: {},
        }
    },

Basically right now what happens, is when I write something in my field, it creates title: 'data' and if i delete the text inside then that element still exists there so I am left with title: '', but I want it to be deleted if its empty.

I can recreate this like this:

computed: {
       destroyFieldWhenEmpty() {
           if (this.fields.title === ''){
               this.$delete(this.fields, 'title')
           }

But now If i have a lot of fields, I have to re-write that if statement for each input.

Thus, How could i go by doing this better?

4
  • 2
    why are you doing that? what's the specific use case? Commented Nov 26, 2020 at 19:20
  • 1
    destroyFieldWhenEmpty is a misuse of computed props, as it's seemingly used only to delete fields.title, but computed props are supposed to return something (to be used elsewhere in the component) and should not have side effects. Commented Nov 27, 2020 at 0:10
  • @BoussadjraBrahim So basically, I want to change a class of one of my div's When Data is inserted into any of the fields, to do this I'd need to check if the fields object is empty, and change the class based on that. Commented Nov 27, 2020 at 13:56
  • could you show how are you doing that? Commented Nov 27, 2020 at 15:31

2 Answers 2

1

- Use lodash isEmpty() function

_.isEmpty({}) // true
_.isEmpty({title: 'title'}) // false

- Use Object.keys().length

const obj = {...}

If obj is empty, Object.keys(obj).length equals to 0.

Sign up to request clarification or add additional context in comments.

Comments

0

So far I've got your problem, you're trying to delete an object from an array. if so you can filter data with your own business logic like this

const restFields = this.fields.filter(field => field.title.length > 0)

2 Comments

fields is an object, not an array.
@tony19 did you, did you try adding v-if="fields.title" to hide any vue component. or if you want to delete key from an object then try delete this.fields.title . Actually there too many ways to do it but not clear what is your logic there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.