herbert mühlex
herbert mühlex

Reputation: 291

How to update/delete ref value in VueJS 3 composition api?

I'm using a ref value to be able to only execute a click event if the ref value is changing.

For example, if I want to update/del the array inside let myRef = ref([]);, do I just drill inside the proxy and do the operations like that :

selectedElements.value.push(3);

which returns Proxy {0: 3}

or what is the correct way to update/del the ref.value ?

export default {  
  setup() {
    let myRef = ref([]);
    return {
     myRef
    };
  },
};

Upvotes: 2

Views: 7730

Answers (2)

user20711281
user20711281

Reputation: 1

const datas=ref({
  id:0,
  name:'test',
  age:20
})

delete datas.value.id
console.log(datas.value) //{name:'test',age:20}

Upvotes: 0

Fujisan
Fujisan

Reputation: 114

You've got it under control. This is how I manage state.

In setup, I list all of my refs or reactive objects. I'll use computed properties if I feel like it to do various crosschecks on my refs or state, e.g. do I have records, how many, etc.

I'll write small functions that will handle state changes/mutations in a local component. If I need to use a watcher on state (ref or reactive object), then I'll do that and use it to call a method/action. You can only update ref inner values by accessing the ref object's single property .value which points to its inner value. I'm sure you know this, but the ref is a wrapper. IN your setup method, you'll got to unwrap a ref to change its inner value, but this isn't true with a reactive object - wherein you can just set that value as per a normal Vue2 data value.

So, yes, in your example, you can mutate your myRef array however you need by accessing its value property. Again, a good way to do this would be to define a method that does the thing that you need done, adding to the array. And, use a computed property to check for whatever it is that is your conditional that is allowing or denying your click event.

Upvotes: 1

Related Questions