繁体   English   中英

如何处理 Laravel 到 Vue.js boolean 值

[英]How to handle Laravel to Vue.js boolean values

我有一个如下所示的输入字段:

<tr v-for="(item, index) in collection">
   ...
   <input 
          type="checkbox" 
          v-model="item.activated" 
          @change="toggleSwitch(item.resource_url, 'activated', item)">
   >
   ...
</tr>

collection是一个包含多个键的数组,激活的是其中之一。 activated等于10 ,因为数据来自 mysql 数据库。 问题是在这种情况下输入字段总是设置为 true,即使activated的等于 1 或 0。

现在,我尝试像这样编写 v-model 来解决这个问题:

v-model="!!+item.activated"

通过添加!!+我会将 integer 值转换为 boolean 并使用它。 这解决了问题,但产生了另一个问题。 我这样做的另一个问题是,当我尝试更改已检查的输入时出现错误:

[Vue warn]: Cannot set reactive property on undefined, null, or primitive value: false
admin.js:120238 TypeError: Cannot use 'in' operator to search for 'activated' in false

toggleSwitch方法如下所示:

toggleSwitch: function toggleSwitch(url, col, row) {
    var _this8 = this;

    axios.post(url, row).then(function (response) {
        _this8.$notify({ type: 'success' });
    }, function (error) {
        row[col] = !row[col];
        _this8.$notify({ type: 'error' });
    });
},

我是 Vue.js 的新手,知道如何调试它,我的问题可能来自哪里? 我很乐意提供任何其他信息。

编辑:

这是我的组件

Vue.component('profile-edit-profile-form', {
    mixins: [AppForm],
    data: function() {
        return {
            form: {
                ...
                activated:  false ,
                ...
            }
        }
    }
});

如果您使用 AJAX 来填充您的collection ,那么您应该在 AJAX 回调中将您的01字符串转换为布尔值,然后再将它们注入您的组件。 或者更好的是,您可以直接从您的 controller 转换它们,顺便说一句,您可以直接得到true | false

data.forEach(function(entry) {
    if(entry.hasOwnProperty("activated"))
        entry.activated = !!+entry.activated
});

我的建议是:

  • 数据库列“激活” tinyint(1)
  • 在 laravel model 中使用 $cast 数组将“激活”转换为“布尔”
  • 在 vue 中使用原生类型 boolean 为 form.activated 与 true 和 false

Laravel Model:

protected $casts = [
'created_at' => 'datetime',
'updated_at' => 'datetime',
'minimum' => 'float',
'maximum' => 'float',
'step' => 'float',
'minItems' => 'integer',
'maxItems' => 'integer',
'uniqueItems' => 'boolean',
];

视图:

<b-form-radio-group id="uniqueItems" v-model="formData.uniqueItems" :options="optionsBoolean" name="uniqueItems" :/>

optionsBoolean (){
            return [
                { text: 'Yes'), value: true },
                { text: 'No'), value: false }
            ]
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM