【问题标题】:Vue.js apply checked on a checkbox based on value from PropVue.js 根据 Prop 中的值应用选中复选框
【发布时间】:2019-10-17 19:56:41
【问题描述】:

说明

我正在与 Laravel 一起运行 Vue.js,目前仅将其用于小型组件。我有一个复选框,我需要根据 Prop 中的值将属性“checked”设置为 true 或 false。加载组件时,Laravel 正在设置该道具。

当页面加载时,应根据 prop 的值选中复选框。因此,如果 prop 设置为 false,则不应选中该复选框,如果为 true,则需要选中它。

我是否认为 Laravel 应该通过 prop 设置值,然后我应该通过将 :checked 绑定到该 Props 值来控制它?

view.blade.php

<public-toggle status="true"></public-toggle>

PublicToggle.vue

<template>
    <div>
        <label class="text-xs font-bold uppercase text-grey-700 mr-2"><i class="fa-question-circle fad text-blue-500 text-sm"></i> Public</label>
        <label class="switch">
            <input type="checkbox" v-bind:value="status" v-on:change="updatePublicStatus" v-model="status" v-bind:checked="status">
            <span class="slider round"></span>
        </label>
    </div>
</template>
<script>
import Swal from 'sweetalert2'
const Toast = Swal.mixin({
  toast: true,
  position: 'top-end',
  showConfirmButton: false,
  timer: 3000
})
export default {
    data() {
        return {
            // status: '',
        }
    },
    methods: {
        updatePublicStatus: function() {
            if(this.status == true) {
                Toast.fire({
                    type: 'success',
                    title: 'Public'
                })
            } else {
                Toast.fire({
                    type: 'success',
                    title: 'Private'
                })
            }
        }
    }
}
</script>

如果有人能帮助我解决这个问题,我将非常感激!

【问题讨论】:

  • prop 是否仅用于传递 initial 值?可以这样做,但通常最好让 prop 保存 current 值。关键区别在于选中/取消选中复选框时会发生什么。 PublicToggle 应该只是将更改视为内部状态还是应该通知父组件以便可以传递新的 prop 值?

标签: javascript laravel vue.js


【解决方案1】:

我会在 Laravel (Blade) 部分尝试以下方式:

<public-toggle :status="{{$status}}"></public-toggle>

在 VueJS 组件中:

data(){
// your data
},
props: ['status'],

记住 CamelCase 问题,如果 Blade var 类似于:'your-var' in VueJs 组件将是:'yourVar'。

希望对你有帮助!

【讨论】:

  • @Matt 当您单击复选框时,您没有在控制台中看到错误吗?
  • @skirtle 实际上我得到了两个! The data property "status" is already declared as a prop. Use prop default value instead.Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "status" - 我不完全确定如何获得所需的结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-15
  • 2015-11-14
相关资源
最近更新 更多