Search code examples
vue.jsvuexpayloadmutation

Payload with multiple properties values in Vuex


I have this demo: https://codepen.io/Albvadi/pen/abdVZxO

I want pass in the payload the title and the class, but only the class is read...

If I change the @click event to pass an object, the JS don´t compile:

// Compiles but dont work
<button
    class="btn btn-primary" 
    @click="addComponent('primary', 'My Title')"
>PrimaryAlert</button>
// No compile
<button
    class="btn btn-primary" 
    @click="addComponent({'primary', 'My Title'})"
>PrimaryAlert</button>

error compilation

Vue warn]: Error compiling template:

invalid expression: Unexpected token ',' in

    addComponent({'primary', 'My Title'})

  Raw expression: @click="addComponent({'primary', 'My Title'})"


19 |                          <div class="row">
20 |                              <div class="col">
21 |                                  <button class="btn btn-primary" @click="addComponent({'primary', 'My Title'})">Primary
   |                                                                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
22 |                                      Alert</button>
23 |                                  <button class="btn btn-warning" @click="addComponent('warning')">Warning

What is wrong?


Solution

  • You can only send one payload data to the mutations from the parameter, so if you need to send multiple data, you need to send an object instead, change your @click to:

    @click="addComponent({classAlert: 'primary', title: 'My Title'})"
    
    @click="addComponent({classAlert: 'warning'})"
    
    @click="addComponent({classAlert: 'danger'})"
    
    @click="addComponent({classAlert: 'dark'})"
    

    and your mutations parameter to:

    // destructuring the parameter
    addComponent(state, { classAlert, title }) {
      console.log(classAlert);
      console.log(title);
    }
    
    // not destructed version
    addComponent(state, data) {
    
       const classAlert = data.classAlert;
       const title = data.title;
    
       console.log(classAlert);
       console.log(title);
    }
    
    

    Demo: https://codepen.io/vincentjonathan99/pen/vYLWXeR