购物车总价计算学习总结

159 阅读1分钟

1. 购物车总价计算方法

Vue深度监听

watch:{
      totalPrice:{
      handler(newName,oldName){
    this.$bus.$emit('bigTotalPrice',newName-oldName);
      },
      deep:true //为true,表示深度监听
    }
  },

组件向外暴露单个商品的总价(单价乘以数量),在主页把价格加起来

2(1). 以表单的形式传图片至后端

this.ruleForm.formData = new FormData();

html部分

      <div class="upload">
        <el-upload
          class="upload-demo"
          drag
          action="none"
          multiple
          :auto-upload="false"
          :on-change="checkType"//调用方法
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
        </el-upload>
      </div>

js部分

          this.ruleForm.formData = new FormData();
          this.ruleForm.formData.append("goodsName", this.ruleForm.goodsName);
          this.ruleForm.formData.append("goodsPrice", this.ruleForm.goodsPrice);
          this.ruleForm.formData.append("origPrice", this.ruleForm.origPrice);
          this.ruleForm.handleCategory=this.ruleForm.goodsCategory.split(':')[0]
          this.ruleForm.formData.append(
            "goodsCategory",
            this.ruleForm.handleCategory
          );
          this.ruleForm.formData.append(
            "offlineTime",
            this.ruleForm.offlineTime
          );
          this.ruleForm.formData.append(
            "description",
            this.ruleForm.description
          );
          this.ruleForm.formData.append("uid", this.ruleForm.uid);
          this.ruleForm.formData.append("file", this.ruleForm.headImgFile.raw);//图片
          axios({
            method: "post",
            url: "http://khai.blue:9999/goods/release",
            data: this.ruleForm.formData,
          }).then(
            (res) => {
              console.log(res.data);
              alert(res.data.msg);
              this.$router.push("/index");
            },
            (err) => {
              console.log(err.message);
            }
          );

        checkType(file, fileList) {
        this.ruleForm.headImgFile = file;
        this.headImgUrl = URL.createObjectURL(file.raw);//file.raw才是后端要的
        },

2(2). action方法

:on-success方法

html部分

      <el-upload
        v-if="!isAdd"
        class="upload-demo"
        action="http://124.221.174.12:5142/goods/updateGoodsDetailsPhoto"
        :data="{ id: editRuleForm.id }"
        :before-remove="beforeRemove"
        :multiple="false"
        :on-success="on_success"
        :limit="1"
      >
        <span>上传商品详情图片</span
        ><el-button size="small" type="primary" class="detailPic"
          >点击上传</el-button
        >
      </el-upload>

js部分

    on_success(response, file, fileList) {
      this.ruleForm.content = response.data;

      console.log(response);

      if (response.code == 200) {
        this.$message.success(response.msg);
      } else {
        this.$message.warning(response.msg);
      }
    },

3. 提示积累

this.$message

成功提示

this.$message.success(response.msg);

失败提示

this.$message.warning(response.msg);

4. 表单验证

html部分

<el-form
    :model="ruleForm"
    :rules="rules"
    ref="ruleForm"//标识
    label-width="120px"
    class="demo-ruleForm"
>
</el-form>
<el-form-item
label="商品总数"
prop="sum"
required
:rules="[
    { required: true, message: '商品总数不能为空' },
    { type: 'number', message: '商品总数必须为数字值' },
  ]"
>
<el-input v-model.number="ruleForm.sum"></el-input>
</el-form-item>

<el-button type="primary" @click="submitForm('ruleForm')"/>//把ref传进去 
    >立即创建</el-button

js部分

 data() {
     return{
      ruleForm: {
          sum:"",
      },
     }
    },
submitForm(formName) {
    this.$refs[formName].validate((valid) => {
    if (valid) {
        this.$message.success('submit!')
    } else {
        console.log("error submit!!");
        return false;
    }
    });
},

5. ajax请求的封装

request.js

import axios from 'axios'
import {
  Message
} from 'element-ui'
// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url

  //基础路径
  baseURL: 'http://124.221.174.12:5142/',
  
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    config.headers.token = localStorage.getItem('token')

    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    return response.data
  },
  error => {
    switch (error.response.status) {
      case 401:
        console.log("无权访问")
        router.push({path: '/login'})
        break
      case 403:
        console.log("token过期啦")
        router.push({path: '/login'})
        break
      case 404:
        console.log("404啦")
        router.push({path: '/404'})
        break
      default:
        return Promise.reject(error)
    }
    return Promise.reject(error)
  }

)

export default service.request

http.js

import request from './request'
const http = {
  get(url, params) {
    const config = {
      method: 'get',
      url: url
    }
    if (params) config.params = params
    return request(config)
  },
  post(url, params) {
    const config = {
      method: 'post',
      url: url
    }
    if (params) config.data = params
    return request(config)
  },
  put(url, params) {
    const config = {
      method: 'put',
      url: url
    }
    if (params) config.params = params
    return request(config)
  },
  delete(url, params) {
    const config = {
      method: 'post',
      url: url
    }
    if (params) config.params = params
    return request(config)
  }
}
export default http

封装接口

import $http from '@/utils/http.js'
//函数名
//传参
export function submitNewGood(dataForm) {
    //请求方法和具体路径
    return $http.post('/goods/addGoods',dataForm)
 }

使用接口

//引入
import { submitNewGood } from "@/api/submitNewGood.js";
//使用
submitNewGood(this.ruleForm).then((result) => {
if (result.code == 200) {
    this.$emit("close");
    this.$message.success(result.msg);
} else {
    this.$message.warning(result.msg);
}
});

刷新页面可以定义一个方法然后调用

6. 自定义方法

父组件

自定义一个close方法

@close="closeLog"
closeLog(){
    //操作数据实现显示或者隐藏
    this.bool = false;
    this.bool2 = false;
    this.getGood();//获取所有数据的方法
    this.$forceUpdate();
    修改了数据,但是页面层没有变动,说明数据本身是被修改了,但是vue没有监听到而已,用$forceUpdate就相当于按照最新数据给渲染一下。
}

子组件

定义一个方法可以随时调用,或者绑定到某个按钮的点击事件

close(){
    this.$emit("close"); //通知父组件改变。
}

7. 路由的跳转

  this.$router.push("/homePage/order/buyerOrder");

8.split切割函数的用法

//切割出来的是一个数组
this.ruleForm.goodsCategory.split(":")[0]