Я использую Vue. js для этого.
У меня есть количество на складе. Я добавил функцию, чтобы уменьшить это число после отправки. Функция работает, она уменьшает значение, но после обновления или перезагрузки страницы количество возвращается в исходное состояние!
Как сделать количество постоянным?
Продукт. js Модель
const mongoose = require('mongoose');
const HomeSchema = mongoose.Schema({
name: String,
title:String,
category:String,
image:String,
description:String,
detail:String,
stock:Number,
price:Number,
star:Number,
cast:String,
director:String,
isDeleted:{type: Boolean, default: false},
updated_date: { type: Date, default: Date.now },
});
module.exports = mongoose.model('Products', HomeSchema);
А это и есть Маршрут продукта. js
var Products = require('../models/Products');
var express = require('express');
var mongoose = require('mongoose');
var router = express.Router();
var multer = require('multer');
var fs = require('fs');
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, '../static/images/')
},
filename: (req, file, cb) => {
let ext = file.originalname.substring(file.originalname.indexOf(".") + 1);
cb(null, file.fieldname + '-' + Date.now() + "." + ext)
}
});
var upload = multer({
storage: storage
});
/* GET ALL products */
router.get('/', function(req, res, next) {
Products.find(function (err, products) {
if (err) return next(err);
res.json(products);
});
});
/* GET SINGLE PRODUCT BY ID */
router.get('/:id', function(req, res, next) {
Products.findById(req.params.id, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* SAVE PRODUCT
router.post('/', function(req, res, next) {
Products.create(req.body, function (err, post) {
if (err) retu rn next(err);
res.json(post);
});
});*/
router.post('/', upload.single('image'),
function (req, res) {
let products = req.body;
products.name = req.body.name
products.title = req.body.title
products.category = req.body.category
products.image = req.body.image != 'undefined' ? req.file.filename : null
products.price = req.body.price
products.description = req.body.description
products.detail = req.body.detail
products.stock = req.body.stock
products.star = req.body.star
products.director = req.body.director
products.cast = req.body.cast
Products.create(products, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
Это HTML
<input
type="submit" @click="decrement(product)"
class="btn btn-warning btn-user btn-block" value="Buy"
/>
<p class="text-danger text-center pt-2">
<i class="fa fa-shopping-cart"></i>
Only {{product.stock}} items left in stock!
</p>
Это функция, которую я использую (ПОЛНЫЙ СКРИПТ)
<script>
/* eslint-disable */
import { mapGetters } from "vuex";
import axios from 'axios'
export default {
name: 'CreateBuyform',
data () {
return {
rezervimet: {},
prodId:this.$route.params.Pid,
productfield:{},
}
},
created() {
axios.get(`http://localhost:4000/products`)
.then(response => {
this.productfield = response.data
})
.catch(e => {
this.errors.push(e)
})
},
computed: {
...mapGetters({
// map `this.user` to `this.$store.getters.user`
user: "user"
})
},
methods: {
onSubmit(evt) {
evt.preventDefault();
var bodyFormData = new FormData();
bodyFormData.set("prodid", document.getElementById("prodid").value);
bodyFormData.set("userid", document.getElementById("userid").value);
bodyFormData.set("address", document.getElementById("address").value);
bodyFormData.set("phoneNumber", document.getElementById("phoneNumber").value);
bodyFormData.set("city", document.getElementById("city").value);
axios.post(`http://localhost:4000/rezervimet`, bodyFormData)
.then(response => {
//console.log(response);
this.$router.push({
name: '',
//params: { id: response.data._id }
})
})
},
decrement(product){
product.stock--;
if(product.stock == 0){
alert("No items in stock");
}
}
}
}
</script>