【问题标题】:Payload with multiple properties values in VuexVuex 中具有多个属性值的有效负载
【发布时间】:2020-07-01 22:17:30
【问题描述】:

我有这个演示:https://codepen.io/Albvadi/pen/abdVZxO

我想在有效载荷中传递标题和类,但只读取类...

如果我更改 @click 事件以传递对象,则 JS 不会编译:

// 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>

错误编译

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

怎么了?

【问题讨论】:

  • {'primary', 'My Title'} 不是有效的 JavaScript 语法。你想创建一个对象吗?键应该是什么?
  • 突变期望classAlerttitle,与state一致

标签: vue.js vuex payload mutation


【解决方案1】:

您只能向参数中的mutations发送一个payload数据,因此如果您需要发送多个数据,则需要发送一个对象,请将您的@click更改为:

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

@click="addComponent({classAlert: 'warning'})"

@click="addComponent({classAlert: 'danger'})"

@click="addComponent({classAlert: 'dark'})"

和你的突变参数:

// 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);
}

演示:https://codepen.io/vincentjonathan99/pen/vYLWXeR

【讨论】:

  • 太好了,谢谢!!还有一个问题:必须使用键,不能不那么冗长吗?为什么如果我有两个名为 classAlerttitle 的变量我可以在没有键的情况下编写 addComponent({classAlert, title})
  • 是的,你必须提供键,如果你用没有键的变量初始化对象,键会自动设置为变量名(它称为简写属性名),所以{classAlert, title}是与{classAlert: classAlert, title:title} 相同,如果您需要不同的密钥,可以使用{alert: classAlert, otherTitle: title},在此处阅读更多内容developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • 明白!非常感谢您的解释!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-15
  • 1970-01-01
  • 2017-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多