为了账号安全,请及时绑定邮箱和手机立即绑定

如何处理 Laravel 到 Vue.js 的布尔值

如何处理 Laravel 到 Vue.js 的布尔值

MMMHUHU 2024-01-03 15:51:18
我有一个如下所示的输入字段:<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等于1或0当数据来自 mysql 数据库时。问题在于,在这种情况下,输入字段始终设置为 true,即使activated等于 1 或 0。现在,我尝试像这样编写 v-model 来解决这个问题:v-model="!!+item.activated"通过添加,!!+我会将整数值转换为布尔值并使用它。这解决了问题,但又产生了另一个问题。我这样做遇到的另一个问题是,当我尝试更改检查的输入时,出现错误:[Vue warn]: Cannot set reactive property on undefined, null, or primitive value: falseadmin.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 新手,知道如何调试它以及我的问题来自哪里?我很乐意提供任何其他信息。
查看完整描述

2 回答

?
浮云间

TA贡献1829条经验 获得超4个赞

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


data.forEach(function(entry) {

    if(entry.hasOwnProperty("activated"))

        entry.activated = !!+entry.activated

});


查看完整回答
反对 回复 2024-01-03
?
慕无忌1623718

TA贡献1744条经验 获得超4个赞

我的建议是:

  • 数据库列“已激活”tinyint(1)

  • 在 Laravel 模型中使用 $cast 数组将“activated”转换为“boolean”

  • 在 vue 中,使用原生类型 boolean 作为 form.activated 的 true 和 false

拉拉维尔模型:

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 }

            ]

        }


查看完整回答
反对 回复 2024-01-03
  • 2 回答
  • 0 关注
  • 38 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信