【问题标题】:Setting a checkbox as checked with Vue.js and Laravel使用 Vue.js 和 Laravel 将复选框设置为选中状态
【发布时间】:2020-01-28 08:35:11
【问题描述】:

我一直在谷歌搜索并使用我知道的每个组合,但我无法将我的复选框初始化为选中状态。
我的控制器

  public function changeStatus(Request $request, about $about)
{
    $this->validate($request, [
        'status' => 'in:true,false'
    ]);

    $about->update(['status' => !$about->status]);

    return response()->json($about);
}

我的迁移

   $table->boolean('status')->default(false)->nullable();

我的模板 vuejs

 <template v-for="item in abouts" :key="item.id"> <a href="javascript:void(0)"
  class="togglebutton btn btn-link btn-sm btn-sm"
    @click="changeStatusItem(item)">
        <label>
         <input type="checkbox" name="status" v-model="item.status"
            v-bind:id="item.id" :checked="item.status"/>
           <span class="toggle"></span>
       </label>
</a></template>

我的脚本

export default{props: {
        checked: Boolean
    },
    data() {
        return {
            abouts: {},
        }
    },
    methods: {
        changeStatusItem(item) {
            //Start Progress bar
            this.$Progress.start();
            axios.get(`/change_status_abouts/${item.id}`).then((res) => {
                /** Alert notify bootstrapp **/
                console.log(res); 
            })
        },}}

【问题讨论】:

  • 1.你从哪里得到你的关于的集合?该示例是一个空对象。但是,假设您确实有一个集合,那么当您从服务器收到带有该项目的响应时,您需要一个。设置 item.status = true; 或循环遍历 about's,如果 id 匹配响应,则将状态设置为 true
  • 你不应该同时使用v-model和:checked。

标签: javascript laravel vue.js


【解决方案1】:

当您调用以下方法时,您可以使用 Array.find() 一旦获得响应 laravel 并更新到您的 about 数组中的 VueJs

changeStatusItem(item) {
    axios.get(`/change_status_abouts/${item.id}`).then((res) => {
       let rec = this._data.about.find(o=>o.id == item.id);
       if(rec){
          rec.status = res.status;
       }
    })
}

您也可以直接在&lt;input type="checkbox" @click="checkChange($event,item)"&gt; 上使用click 事件,该事件您可以调用您的ajax 调用。所以在这种情况下你不需要更新about数组中的状态


请检查下面的代码sn-p。


var demo = new Vue({
  el: '#demo',
  data: {
    about:[]
  },
  methods: {
    changeStatusItem(item) {
      let rec = this._data.about.find(o=>o.id == item.id);
      if(rec){
        rec.status = !rec.status;
      }
    },
    getValue(item) {
      return `${item.id}. - ${item.title.toLocaleUpperCase()}`;
    }
  },
  created: function() {
    let self = this;
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then(response => response.json())
      .then(json =>{self.$data.about = json.map(o=>Object.assign(o,{status:false}))
      document.querySelector('.main-div').style.display='none'
      })
  }
})
.main-div{background-color:#40e0d0;color:#fff;font-size:24px;padding:26px 0;text-align:center;height:100%;width:100%;display:inline-block}.lds-roller{display:inline-block;position:relative;width:64px;height:64px}.lds-roller div{animation:lds-roller 1.2s cubic-bezier(.5,0,.5,1) infinite;transform-origin:32px 32px}.lds-roller div:after{content:" ";display:block;position:absolute;width:6px;height:6px;border-radius:50%;background:#fff;margin:-3px 0 0 -3px}.lds-roller div:nth-child(1){animation-delay:-36ms}.lds-roller div:nth-child(1):after{top:50px;left:50px}.lds-roller div:nth-child(2){animation-delay:-72ms}.lds-roller div:nth-child(2):after{top:54px;left:45px}.lds-roller div:nth-child(3){animation-delay:-108ms}.lds-roller div:nth-child(3):after{top:57px;left:39px}.lds-roller div:nth-child(4){animation-delay:-144ms}.lds-roller div:nth-child(4):after{top:58px;left:32px}.lds-roller div:nth-child(5){animation-delay:-.18s}.lds-roller div:nth-child(5):after{top:57px;left:25px}.lds-roller div:nth-child(6){animation-delay:-216ms}.lds-roller div:nth-child(6):after{top:54px;left:19px}.lds-roller div:nth-child(7){animation-delay:-252ms}.lds-roller div:nth-child(7):after{top:50px;left:14px}.lds-roller div:nth-child(8){animation-delay:-288ms}.lds-roller div:nth-child(8):after{top:45px;left:10px}@keyframes lds-roller{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}.list{padding: 10px;border-bottom: 1px solid #ccc;}
<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900|Material+Icons">
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/vuetify@1.4.0/dist/vuetify.min.css">

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@1.4.0/dist/vuetify.min.js"></script>

<div id="demo" >
    <div class="main-div"><div class="lds-roller"><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div></div><p>Pleaes wait...!</p>
 </div>
    <div class="list" v-for="item in about">
     <a href="javascript:void(0)"
    class="togglebutton btn btn-link btn-sm btn-sm"
      @click="changeStatusItem(item)">
          <label>
           <input type="checkbox" name="status" v-model="item.status"
              v-bind:id="item.id"/>
             <span class="toggle"></span>
         </label> {{getValue(item)}}
  </a>
    </div>
</div>

【讨论】:

    【解决方案2】:

    我会这样做。请记住,它可能像从 Laravel 模型中进行强制转换一样简单,即返回字符串“1”而不是布尔值,以便修复您可以使用检查布尔值或字符串等的方法。还需要将响应设置回到收藏。也不要使用 v-model - 您的示例中不需要它

    
    <template>
        <div v-for="item in abouts"
             :key="item.id">
            <a href="javascript:void(0)"
                class="togglebutton btn btn-link btn-sm btn-sm"
                @click="changeStatusItem(item)">
                <label>
                    <input type="checkbox"
                           name="status"
                           :id="item.id"
                           :checked="isChecked(item)"/>
                    <span class="toggle"></span>
                </label>
            </a>
        </div>
    </template>
    
    <script>
        export default {
            name: "Example",
            data: function() {
                return {
                    abouts: {}
                }
            },
            methods: {
                isChecked(obj) {
                    return (typeof obj.status === "boolean" )
                        ? obj.status
                        : typeof obj.status === "string" && obj.status === '1';
                },
                changeStatusItem: function (item) {
                    let vm = this;
    
                    axios.get(`/change_status_abouts/${item.id}`)
                        .then((response) => {
                            for (key in vm.abouts) {
                                if (vm.abouts.hasOwnProperty(key)) {
                                    vm.abouts[key].status = (vm.abouts[key].id === item.id)
                                }
                            }
                        });
                },
                getAbouts: function () {
                    let vm = this;
    
                    axios.get(`/get/abouts`)
                        .then((response) => {
                            vm.abouts = response.data;
                        });
                },
                init() {
                    this.getAbouts();
                }
            },
            mounted: function () {
                this.$nextTick(this.init());
            }
        }
    </script>
    
    
    

    【讨论】:

    • 控制台返回此错误ReferenceError: assignment to undeclared variable key
    猜你喜欢
    • 2017-04-21
    • 1970-01-01
    • 2016-02-17
    • 2023-01-26
    • 1970-01-01
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多