Как бы я передать переменную данных в качестве параметра в VueJs? Попытка предотвратить пустое значение при изменении другой проп - PullRequest
0 голосов
/ 20 июня 2019

Я пытаюсь динамически изменить значение моего количества "проп", не сбрасывая другие значения пропа на пустое. У меня есть решение, которое работает, но оно жестко запрограммировано, я думаю, что знаю решение для жесткого кода, но пока не выполнено. Чтобы сэкономить время, обратите внимание в первую очередь на <i v-on:click> и <input @change> для имени, фамилии, адреса электронной почты, количества и методов / данных, конечно. Заранее спасибо!

Это то, что работает прямо сейчас: у каждой опоры есть своя функция «держать». Вот взгляд:

Vue.component('orderform', {
props: [
    'productname', 'productid', 'productprice', 'stock', 'quantity', 'firstname',
    'lastname', 'email', 'readonly', 'customerId'
],
template: `
<div class="container">
<div class="py-5 text-center">
    <h2 class="title-font">Checkout form</h2>
</div>

<div class="row">
    <div class="col-md-4 order-md-2 mb-4">
        <h4 class="d-flex justify-content-between align-items-center mb-3">
            <span class="text-muted">Your order</span>
        </h4>
        <ul class="list-group mb-3">
            <li class="list-group-item d-flex justify-content-between lh-condensed">
                <div>
                    <h6 class="my-0">{{productname}}</h6>
                    <small class="text-muted">{{this.quan}}</small>
                    <i v-on:click="increasequantity" class="fas fa-arrow-circle-up up-arrow"></i>
                    <i v-on:click="decreasequantity" class="fas fa-arrow-circle-down down-arrow"></i>
                    <span id="stock-message" style="color:red"></span>
                </div>
                <span class="text-muted">\${{productprice}}</span>
            </li>


            <li class="list-group-item d-flex justify-content-between">
                <span>Total (USD)</span>
                <strong>\${{(this.quan*productprice).toFixed(2)}}</strong>
            </li>
        </ul>


    </div>
    <div class="col-md-8 order-md-1">
        <form method="POST" class="needs-validation" novalidate>
         <input type="text" v-bind:value=productname name="name" hidden>
            <input id="total" type="text" v-bind:value=(this.quan*productprice).toFixed(2) name="total">
            <input id="price" type="text" v-bind:value=productprice name="price">
            <input type="text" v-bind:value=productid name="productId" hidden>
            <input type="text" v-bind:value=this.quan name="quantity">
            <input name="action" value="order" hidden>

            <div class="row">
                <div class="col-md-6 mb-3">
                    <label for="firstName">First name</label>
                    <input @change="keepfname($event.target.value)" v-bind:readonly=readonly v-bind:value=this.fname type="text" class="form-control" id="firstName" placeholder="First Name" required>
                    <div class="invalid-feedback">
                        Valid first name is required.
                    </div>
                </div>
                <div class="col-md-6 mb-3">
                    <label for="lastName">Last name</label>
                    <input @change="keeplname($event.target.value)"  v-bind:readonly=readonly v-bind:value=lname type="text" class="form-control" id="lastName" placeholder="Last Name" required>
                    <div class="invalid-feedback">
                        Valid last name is required.
                    </div>
                </div>
            </div>



            <div class="mb-3">
                <label for="email">Email <span class="text-muted"></span></label>
                <input @change="keepemail($event.target.value)" name="email" v-bind:readonly=readonly v-bind:value=mail type="email" class="form-control" id="email" placeholder="you@example.com" required>
                <div class="invalid-feedback">
                    Please enter a valid email address for shipping updates.
                </div>
            </div>


            <hr class="mb-4">
            <button name="orderitem" class="btn btn-danger btn-lg btn-block" type="submit">Checkout</button>
        </form>
    </div>
</div>

`,

data() {
    return {
        fname: this.firstname,
        lname: this.lastname,
        mail: this.email,
        quan: this.quantity,
    }
},
methods: {
    keepfname: function (val) {
        console.log(this.name)
        console.log(val)
        this.fname = val;
    },
    keeplname: function (val) {
        console.log(this.name)
        console.log(val)
        this.lname = val;
    },
    keepemail: function (val) {
        console.log(this.name)
        console.log(val)
        this.mail = val;
    },
    increasequantity: function (amount) {
        console.log(this.quan)
        if (this.quan == this.stock) {
            $("#stock-message").html(`There's only ${this.stock} in stock.`)
        } else {
            this.quan++;
        }
    },

    decreasequantity: function () {
        if (this.quan > 1) {
            this.quan--;
            $("#stock-message").html(``)
        }
    }
},

});

Что я хочу работать: keepvalue () принимает значение и присваивает его реквизиту, на случай, если я захочу добавить больше входных данных, это решит необходимость создания отдельной функции для каждой реквизита. Вот взгляд:

Vue.component('orderform', {
props: [
    'productname', 'productid', 'productprice', 'stock', 'quantity', 'firstname',
    'lastname', 'email', 'readonly', 'customerId'
],

template: `
<div class="container">
<div class="py-5 text-center">
    <h2 class="title-font">Checkout form</h2>
</div>

<div class="row">
    <div class="col-md-4 order-md-2 mb-4">
        <h4 class="d-flex justify-content-between align-items-center mb-3">
            <span class="text-muted">Your order</span>
        </h4>
        <ul class="list-group mb-3">
            <li class="list-group-item d-flex justify-content-between lh-condensed">
                <div>
                    <h6 class="my-0">{{productname}}</h6>
                    <small class="text-muted">{{this.quan}}</small>
                    <i v-on:click="increasequantity" class="fas fa-arrow-circle-up up-arrow"></i>
                    <i v-on:click="decreasequantity" class="fas fa-arrow-circle-down down-arrow"></i>
                    <span id="stock-message" style="color:red"></span>
                </div>
                <span class="text-muted">\${{productprice}}</span>
            </li>


            <li class="list-group-item d-flex justify-content-between">
                <span>Total (USD)</span>
                <strong>\${{(this.quan*productprice).toFixed(2)}}</strong>
            </li>
        </ul>


    </div>
    <div class="col-md-8 order-md-1">
        <form method="POST" class="needs-validation" novalidate>
         <input type="text" v-bind:value=productname name="name" hidden>
            <input id="total" type="text" v-bind:value=(this.quan*productprice).toFixed(2) name="total">
            <input id="price" type="text" v-bind:value=productprice name="price">
            <input type="text" v-bind:value=productid name="productId" hidden>
            <input type="text" v-bind:value=this.quan name="quantity">
            <input name="action" value="order" hidden>

            <div class="row">
                <div class="col-md-6 mb-3">
                    <label for="firstName">First name</label>
                    <input @change="keepvalue($event.target.value,'fname')" v-bind:readonly=readonly v-bind:value=this.fname type="text" class="form-control" id="firstName" placeholder="First Name" required>
                    <div class="invalid-feedback">
                        Valid first name is required.
                    </div>
                </div>
                <div class="col-md-6 mb-3">
                    <label for="lastName">Last name</label>
                    <input @change="keepvalue($event.target.value,'lname')"  v-bind:readonly=readonly v-bind:value=lname type="text" class="form-control" id="lastName" placeholder="Last Name" required>
                    <div class="invalid-feedback">
                        Valid last name is required.
                    </div>
                </div>
            </div>



            <div class="mb-3">
                <label for="email">Email <span class="text-muted"></span></label>
                <input @change="keepvalue($event.target.value,'mail')" name="email" v-bind:readonly=readonly v-bind:value=mail type="email" class="form-control" id="email" placeholder="you@example.com" required>
                <div class="invalid-feedback">
                    Please enter a valid email address for shipping updates.
                </div>
            </div>


            <hr class="mb-4">
            <button name="orderitem" class="btn btn-danger btn-lg btn-block" type="submit">Checkout</button>
        </form>
    </div>
</div>

`,

data() {
    return {
        fname: this.firstname,
        lname: this.lastname,
        mail: this.email,
        quan: this.quantity,
    }
},
methods: {
    keepvalue: function (val, name) {
        console.log(this.name)
        console.log(val)
        this.name = val;
    },
    increasequantity: function (amount) {
        console.log(this.quan)
        if (this.quan == this.stock) {
            $("#stock-message").html(`There's only ${this.stock} in stock.`)
        } else {
            this.quan++;
        }
    },

    decreasequantity: function () {
        if (this.quan > 1) {
            this.quan--;
            $("#stock-message").html(``)
        }
    }
},

});

Я также пытался передать компонент, но в результате получил неопределенное значение. Например.

@change="keepvalue($event.target.value,fname)"
@change="keepvalue($event.target.value,this.$options.fname)" // tried this too
keepvalue: function (val, name) {
        console.log(this.name) // undefined
        console.log(val)
        this.name = val;
    }

@change="keepvalue($event.target.value,this.fname)" // AND THIS
keepvalue: function (val, name) {
        console.log(name) // undefined
        console.log(val)
        name = val;
    }

HTML: <orderform firstname="firstname" lastname="lastname" email="email" quantity="3" productname="productname" productprice="8.99" productid="1" stock="10"> </orderform>

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...