【问题标题】:How to handle Laravel to Vue.js boolean values如何处理 Laravel 到 Vue.js 的布尔值
【发布时间】:2020-07-30 05:58:04
【问题描述】:

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

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

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

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

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

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

[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 ,
                ...
            }
        }
    }
});

【问题讨论】:

  • 能否请您展示如何在此组件中检索您的collection
  • @Shizzen83 是的,抱歉,erm 集合的默认值为 null,我使用来自控制器的 ajax laravel/vue 请求填充它。

标签: javascript php html laravel vue.js


【解决方案1】:

如果您使用 AJAX 填充您的 collection,那么您应该在 AJAX 回调中将您的 01 字符串转换为布尔值,然后再将它们注入您的组件。或者更好的是,您可以直接从控制器转换它们,通过直接获取 true|false

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

【讨论】:

  • 这是一个很好的解决方法,感谢您的建议,如果没有其他答案,我一定会使用它。我得到的值确实是字符串,而不是整数。
  • 你应该看看laravel.com/docs/7.x/eloquent-mutators#attribute-casting。使用boolean 演员表并且如果您使用 Eloquent 模型,这将是最好的方法,因为当您从数据库中检索数据时会自动转换数据。
【解决方案2】:

我的建议是:

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

Laravel 模型:

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

Vue:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 2018-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多