vue3中的一些便捷写法记录

vue2+vue3 本博客主要为coderwhy的Vue2网课 + 尚硅谷Vue2+Vue3网课,所整理记录的学习笔记,仅作学习用途,如有侵权,烦请联系本人侵删。同时感谢黑马、尚硅谷老师们的辛苦教导付出,如有不足之处,欢迎各位小伙伴、官老爷们多多提意见或建议,感谢! 阅读详情

1、子组件触发父组件事件

<template>
  <div class="father">
    <h3>父组件,</h3>
		<h4>儿子给的玩具:{{ toy }}</h4>
		<Child :car="car" @getToy="getToy"/>
  </div>
</template>

<script setup lang="ts" name="Father">
	import Child from './Child.vue'
	import { ref } from "vue";
	// 数据
	const toy = ref()
	// 方法
	function getToy(value:string){
		toy.value = value
	}
</script>
<template>
  <div class="child">
    <h3>子组件</h3>
		<h4>我的玩具:{{ toy }}</h4>
		<button @click="handleToy">玩具给父亲</button>
  </div>
</template>

<script setup lang="ts" name="Child">
	import { ref } from "vue";
	const toy = ref('奥特曼')
	
	const emit = defineEmits(["getToy"]);
    const handleToy = (type: number, orgId: number) => {
      emit("getToy", toy);
    };
</script>

2、公共Hooks函数封装(强烈建议好好看下,使用起来很方便)

2.1、table公共方法封装(table列表、分页、搜索、删除、状态修改)
// composables/useCommon.js文件内
import { ref, reactive, computed } from "vue";
import { message } from "@/composables/util.js";
import { ElMessageBox } from "element-plus";
// 公共table接口
interface TableOptions {
  // 搜索参数
  searchForm?: object;
  // api文件内的接口
  getList: Function;
  // 获取数据后对数据进行处理的回调
  // 注:(如果需要对列表的回调数据进行特殊处理就需要传,只是列表渲染就不需要传这个)
  onGetListSuccess?: Function;
  // 启用
  enableStatus?: Function;
  // 禁用
  disableStatus?: Function;
  // 删除
  delete?: Function;
}

// 复选框接口
interface idOptions {
  id: number;
}

// 公共逻辑拆分(分页+列表+删除+搜索+修改状态)
// opt参数 必传:getList(获取列表数据的接口)
// 选传:searchForm(搜索参数)、updateStatus(修改状态的接口)、
// delete(删除状态的接口)、onGetListSuccess(获取数据后对数据进行处理的回调)
export function useInitTable(opt: TableOptions) {
  const tableData = ref([]);
  const loading = ref(false);
  // 分页参数
  const currentPage = ref(1);
  const limit = ref(10);
  const total = ref(0);
  // 搜索
  let searchForm = null;
  let resetSearchForm = null;

  // 搜索参数可能会有多个,需要使用组件传递对应搜索参数,公共组件动态获取
  if (opt.searchForm) {
    searchForm = reactive({ ...opt.searchForm });

    resetSearchForm = () => {
      // opt.searchForm的格式searchForm: {keyword: ''},使用组件传的值必定为空,循环给searchForm初始化值
      for (const key in opt.searchForm) {
        searchForm[key] = opt.searchForm[key];
      }

      getData();
    };
  }
  // 分页
  const handleSizeChange = (pageSize: number) => {
    searchForm.pageSize = pageSize;
    getData();
  };
  const handleCurrentChange = (currentPage: number) => {
    console.log(currentPage, "currentPage");
    searchForm.pageNum = currentPage;
    getData();
  };
  const getData = async (p = null) => {
    // p为当前页码数
    if (typeof p == "number") {
      currentPage.value = p;
    }
    loading.value = true;
    // const res = await opt.getList(currentPage.value, searchForm);
    const queryParams = {};
    for (const key in searchForm) {
      if (searchForm[key]) {
        queryParams[key] = searchForm[key];
      }
    }
    const res = await opt.getList(queryParams);
    if (res.code === 200) {
      // 部分组件需要返回特殊的参数,如:每个item中都要返回一个checked属性,那么将执行使用组件传来的逻辑,返回对应参数
      if (opt.onGetListSuccess && typeof opt.onGetListSuccess == "function") {
        opt.onGetListSuccess(res);
      } else {
        console.log(res, "res");
        tableData.value = res.data.list;
        total.value = res.data.total;
      }
    }
    loading.value = false;
  };
  getData();
  // 启用
  const handleEnable = async (id: number) => {
    try {
      await opt.enableStatus(id);
      message("启用成功", { type: "success" });
      getData();
    } catch (err) {
      console.log(err, "err");
    }
  };
  // 禁用
  const handleDisable = async (id: number) => {
    try {
      await opt.disableStatus(id);
      message("禁用成功", { type: "success" });
      getData();
    } catch (err) {
      console.log(err, "err");
    }
  };
  // 删除
  const handleDelete = async (ids: object) => {
    loading.value = true;
    try {
      // 弹出确认框
      ElMessageBox.confirm("是否删除此字典类型?", "提示", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(async () => {
          // 用户点击确定按钮的处理逻辑
          await opt.delete({ ids }).then(res => {
            if (res.code === 200) {
              message("删除成功", { type: "success" });
              getData();
              return;
            } else {
              message(res.message, { type: "error" });
              return;
            }
          });
        })
        .catch(() => {
          // 用户点击取消按钮的处理逻辑
          message("已取消操作", { type: "info" });
        });
    } catch (err) {
      loading.value = false;
    }
  };

  // 复选框多选选中id
  const multiSelectionIds = ref([]);
  const handleSelectionChange = (e: Array<object>) => {
    const ids = e.map((o: idOptions) => {
      return o.id;
    });
    multiSelectionIds.value = ids;
  };
  // 批量删除
  // const multipleTableRef = ref(null);
  const handleMultiDelete = () => {
    if (!multiSelectionIds.value.length)
      return message("请选择至少一个选项", { type: "info" });
    try {
      const params = {
        ids: multiSelectionIds.value.join()
      };
      ElMessageBox.confirm("是否删除选中的字典类型?", "提示", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(async () => {
          // 用户点击确定按钮的处理逻辑
          await opt.delete(params).then(res => {
            if (res.code === 200) {
              message("删除成功", { type: "success" });
              getData();
              return;
            } else {
              message(res.message, { type: "error" });
              return;
            }
          });
        })
        .catch(() => {
          // 用户点击取消按钮的处理逻辑
          message("已取消操作", { type: "info" });
        });
    } catch (err) {
      console.log(err, "err");
    }
  };
  // 批量修改状态
  const handleMultiStatusChange = async (status: string) => {
    if (!multiSelectionIds.value.length)
      return message("请选择至少一个选项", { type: "info" });
    try {
      // await opt.updateStatus(multiSelectionIds.value, status);
      console.log(status, "status");
      message("修改状态成功", { type: "success" });
      getData();
    } catch (err) {
      console.log(err, "err");
    }
  };

  return {
    searchForm,
    resetSearchForm,
    tableData,
    limit,
    loading,
    total,
    currentPage,
    getData,
    handleDisable,
    handleEnable,
    handleDelete,
    handleSelectionChange,
    handleMultiDelete,
    handleMultiStatusChange,
    handleSizeChange,
    handleCurrentChange,
    multiSelectionIds
  };
}

使用table公共方法

<script setup lang="ts" name="EvaluateDetail">
// 公共table方法
import { useInitTable } from "@/composables/useCommon.js";
// table列表接口
import { getCategoryList } from "@/api/evaluate";
// 公共组件
import JmSearch from "@/components/JmSearch/index.vue";
import JmSearchItem from "@/components/JmSearchItem/index.vue";
import JmTable from "@/components/JmTable/index.vue";
import JmPagination from "@/components/JmPagination/index.vue";
// 搜索相关参数
const params = {
  patientName: "",
  userAccount: "",
  supportWorkerName: "",
  evaluateTime: [],
  evaluateTimeStart: "",
  evaluateTimeEnd: "",
  pageNum: 1,
  pageSize: 10,
  sortOrder: "desc"
};
const searchLabelList = [
  {
    key: "patientName",
    label: "就诊人姓名"
  },
  {
    key: "userAccount",
    label: "评价账号"
  },
  {
    key: "supportWorkerName",
    label: "护理人员"
  }
];
// 选择时间
interface DateType {
  [index: number]: string;
}
const handlePicker = (e: Array<DateType>) => {
  if (e && e.length > 0) {
    searchForm.evaluateTimeStart = e[0];
    searchForm.evaluateTimeEnd = e[1];
  } else {
    searchForm.evaluateTimeStart = "";
    searchForm.evaluateTimeEnd = "";
  }
};
// 公共方法table使用
const {
  tableData,
  getData,
  handleSizeChange,
  handleCurrentChange,
  resetSearchForm,
  total,
  searchForm
} = useInitTable({
  searchForm: params,
  // getCategoryList为table接口
  getList: getCategoryList
});
const tableColumns = [
  { prop: "supportWorkerId", label: "户工编号", width: "130" },
  { prop: "userAccount", label: "评价账号", width: "180" },
  { prop: "patientName", label: "就诊人姓名", width: "180" },
  { prop: "supportWorkerName", label: "护理人员", width: "180" },
  { prop: "orgName", label: "所属机构", width: "260" },
  { prop: "servicerNo", label: "服务单编号", width: "200", slot: "order" },
  {
    prop: "comprehensiveScore",
    label: "评价分值",
    width: "130",
    sortable: true
  },
  { prop: "detail", label: "查看", width: "200", slot: "actions" },
  { prop: "evaluateTime", label: "评价时间", width: "200" }
];

</script>

<template>
  <div>
    <!-- 搜索 -->
    <jm-search @search="getData" @reset="resetSearchForm" :model="searchForm">
      <jm-search-item
        v-for="(item, index) in searchLabelList"
        :key="index"
        :spanItem="5"
        :label="item.label"
      >
        <el-input
          v-model="searchForm[item.key]"
          :placeholder="item.label"
          clearable
        />
      </jm-search-item>
      <jm-search-item :spanItem="5" label="下单时间">
        <el-date-picker
          v-model="searchForm['evaluateTime']"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          @change="handlePicker"
        />
      </jm-search-item>
    </jm-search>
    <jm-table
      :initial-data="tableData"
      :columns="tableColumns"
      :showCheckbox="false"
      :height="'418'"
    />
    <!-- 分页组件 -->
    <jm-pagination
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
      :total="total"
    />
  </div>
</template>

<style lang="scss" scoped></style>
2.2、form表单公共方法封装(表单新增、修改、提交)
// composables/useCommon.js文件内
import { ref, reactive, computed } from "vue";
import { message } from "@/composables/util.js";
import { ElMessageBox } from "element-plus";
// 公共表单接口
interface FormOptions {
  // 表单参数
  form: object;
  rules?: object;
  title?: string;
  editId?: number;
  currentPage?: number;
  // 获取数据后对数据进行处理的回调
  // 编辑获取表单详情后的钩子
  // 注:页面中需要表单数据渲染的才需要传这个钩子,比如页面中有tag标签需要表单内容回显,但是不能直接用表单数据
  beforeGetForm?: Function;
  // 注:(如果需要对列表的回调数据进行特殊处理就需要传,只是列表渲染就不需要传这个)
  beforeSubmit?: Function;
  // 表单保存后的回调方法
  afterSubmit?: Function;
  // api文件内的接口
  // 详情
  detail?: Function;
  // 修改
  update?: Function;
  // 新增
  create?: Function;
  getData?: Function;
}
// 复选框接口
interface idOptions {
  id: number;
}

// 表单新增修改接口
interface FormDataOptions {
  code: number;
  data?: object;
}

// 表单(新增+修改+提交)逻辑拆分
// opt参数 必传:form(表单初始值)、
// 可选:title(表单标题)、currentPage(当前页:必须在useInitTable之后)、
// update(修改表单接口)、create(新增表单接口)
export function useInitForm(opt: FormOptions) {
  const formRef = ref(null);
  // 表单参数
  const defaultForm = opt.form;
  const form = reactive({});
  // 表单规则
  const rules = opt.rules || {};
  // 修改id
  const editId = ref(0);
  // 弹框title
  const drawerTitle = computed(() => {
    console.log("editId.value", editId.value);
    return editId.value ? "编辑" + opt.title : "新增" + opt.title;
  });

  // 重置表单
  const resetForm = (row = {}) => {
    if (formRef.value) formRef.value.clearValidate();
    for (const key in defaultForm) {
      form[key] = row[key];
    }
  };
  // // 新增
  // const handleCreate = () => {
  //   resetForm(defaultForm);
  // };
  // // 编辑
  // const handleEdit = () => {
  //   resetForm(defaultForm);
  // };
  if (opt.editId) {
    editId.value = opt.editId;
    // 是否有获取详情钩子
    if (opt.detail && typeof opt.detail == "function") {
      opt.detail(editId.value).then((res: FormDataOptions) => {
        if (res.code === 200) {
          // 是否需要对form数据进行特殊处理 详情见beforeGetForm接口介绍
          if (opt.beforeGetForm && typeof opt.beforeGetForm == "function") {
            opt.beforeGetForm(res);
          } else {
            resetForm(res.data);
          }
        }
      });
    }
  } else {
    resetForm(defaultForm);
  }
  // 提交表单
  const handleSubmit = () => {
    formRef.value.validate(async (valid: boolean) => {
      if (!valid) return false;
      console.log(form, "form");
      try {
        // 将form赋值给body,传给回调,处理时间戳
        let body = {};
        if (opt.beforeSubmit && typeof opt.beforeSubmit == "function") {
          body = opt.beforeSubmit({ ...form });
        } else {
          body = form;
        }

        const Fun = editId.value ? opt.update(body) : opt.create(body);
        // 修改刷新当前页,新增刷新第一页
        Fun.then((res: FormDataOptions) => {
          console.log(res, "res提交表单");
          if (res.code === 200) {
            message(drawerTitle.value + "成功", { type: "success" });
          } else {
            message(drawerTitle.value + "失败", { type: "warning" });
          }
          opt.afterSubmit(res);
        });
      } catch (err) {
        console.log(err);
      }
    });
  };
  return {
    formRef,
    form,
    rules,
    editId,
    drawerTitle,
    handleSubmit,
    resetForm
  };
}

使用form公共方法

<script setup lang="ts" name="AccountDetail">
import { ref, reactive } from "vue";
import { useInitForm } from "@/composables/useCommon.js";
import { getRoleLists } from "@/api/system";
import { RoleListsResult } from "@/api/type/system";
import {
  userAccountManageSave,
  userAccountResetPwd,
  userAccountDetail
} from "@/api/business";
const props = defineProps({
  pageType: {
    type: Number,
    default: 0
  },
  workerId: {
    type: Number,
    default: 0
  }
});

const formInit = {
  loginName: "",
  password: 12345678,
  roleId: "",
  roleName: "",
  userName: "",
  userId: 0
};
const selectKey = ref("roleId");
if (props.workerId) {
  selectKey.value = "roleName";
}
interface formOptions {
  code: number;
}
// 公共form方法使用
const { formRef, rules, handleSubmit, form } = useInitForm({
  editId: props.workerId,
  title: "账号",
  form: formInit,
  // userAccountManageSave、userAccountResetPwd、userAccountDetail都是相应的接口
  create: userAccountManageSave,
  update: userAccountResetPwd,
  detail: userAccountDetail,
  rules: {
    loginName: [{ required: true, message: "请输入账号名称", trigger: "blur" }],
    password: [{ required: true, message: "请输入账号名称", trigger: "blur" }],
    userName: [{ required: true, message: "请输入账号名称", trigger: "blur" }],
    roleId: [{ required: true, message: "请选择账号角色", trigger: "blur" }]
  },
  afterSubmit: (res: formOptions) => {
    if (res.code === 200) {
      changePage(1);
    }
  }
});

const roleList = reactive([]);
const getRoleListFn = () => {
  getRoleLists().then((res: RoleListsResult) => {
    if (res.code === 200) {
      const resInit = res.data.map(item => {
        return {
          roleId: item.roleId,
          roleName: item.roleName
        };
      });
      // 对象不能直接赋值,vue3检测不到
      roleList.push(...resInit);
    }
  });
};
getRoleListFn();
const emit = defineEmits(["open"]);
const changePage = (type: number, id?: number) => {
  // 实现打开页面的逻辑
  const val = {
    type,
    id
  };
  emit("open", val);
};
// onBeforeMount(() => {
//   getRoleListFn();
// });
</script>
<template>
  <div>
    <el-form
      :model="form"
      ref="formRef"
      :rules="rules"
      label-width="90px"
      :inline="false"
    >
      <el-form-item label="创建账号" prop="loginName">
        <el-input
          v-model="form['loginName']"
          max="20"
          placeholder="请输入创建账号"
          :disabled="pageType === 3 ? true : false"
        />
      </el-form-item>
      <el-form-item label="设置密码" prop="password">
        <el-input
          v-model="form['password']"
          max="60"
          placeholder="请输入设置密码"
        />
      </el-form-item>
      <el-form-item label="账号姓名" prop="userName">
        <el-input
          v-model="form['userName']"
          max="60"
          placeholder="请输入账号姓名"
          :disabled="pageType === 3 ? true : false"
        />
      </el-form-item>
      <el-form-item label="账号角色" prop="roleId" class="el-input">
        <el-select
          v-model="form[selectKey]"
          placeholder="城市运营"
          :disabled="pageType === 3 ? true : false"
        >
          <el-option
            v-for="(item, index) in roleList"
            :key="index"
            :label="item.roleName"
            :value="item.roleId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">{{
          props.workerId ? "编辑" : "创建"
        }}</el-button>
        <el-button @click="changePage(1)">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<style lang="scss" scoped>
:deep(.el-form-item__content) {
  flex: unset;
  width: 300px;
}
</style>

Vue学习记录之二十六 Vue3中跨域 跨域是浏览器出于安全考虑限制不同源之间资源请求的机制。通过 CORS、JSONP、代理等方式可以实现跨域通信。 阅读详情

相关推荐

usb gadget uvc driver的code分析

uvc的linux driver分为host侧和gadget侧两个driver。host侧的driver在v4l2框架下,而设备侧的driver在usb/gadget文件夹下。gadget侧的uvc driver,利用v4l2框架去注册video_device,向应用层提供调用接口。同时,它完成v4l2 video buffer拷贝到usb request下的buffer下,然后利用uvc实现的协

lintwins的专栏 1万+

Vue3<script setup>——组件通信

Vue3 组件通信

weixin_42289080的博客 2433

无GPS室内飞行:基于PX4与MID360的FAST-LIO定点悬停实战解析

本文详细解析了基于PX4飞控与大疆MID360激光雷达的无GPS室内飞行技术,重点介绍了FAST-LIO算法在定点悬停中的应用。通过硬件配置、软件环境搭建、坐标系转换等实战经验,帮助开发者解决室内定位难题,实现精准悬停与稳定飞行。

weixin_29056781的博客 262

alibaba fastjson GET List传参 和 接收解析

之前一直都是 get传的都是单字符串(例如 xxxxxxxxx?),并没有传list的.

好好学习日记 644

Rokid眼镜高精度图像识别的五大工程破局点

图像识别是AR交互的基础能力,其核心在于将现实图像映射为可计算的数字特征,并通过几何建模解算空间姿态。在专用AR眼镜场景中,该过程面临光学畸变、传感器时序错位、低延迟跟踪与人因适配等复合挑战。尤其在工业现场,Rokid Max系列的鱼眼镜头畸变、IMU-视觉异步采样、窄FOV下快速眼动等物理约束,使传统基于AR Foundation或OpenCV的识别方案失效。本文聚焦真实部署中的关键瓶颈,涵盖实时反畸变纹理渲染、原生SDK直调优化、端侧轻量CNN模型(TinyImageNet-Rokid)、IMU-视觉紧

weixin_33681778的博客 697

中国知网文献引用导入EndNote9.X,Web of science导入endnote以及谷歌学术导入endnote图文详解,全网最细版本适用EndNote9.x,Endnote20版本

在科研中用到EndNote管理文献,遇到插入文献时,中国知网如何将参考文献导进Endnote9.x或者web of sicence,谷歌学术如何将文章,文献导入进文献管理软件EndNote的详细图文2022版本解释,全网最细的笔记教程,值得大家参考收藏学习

sakura的博客 5175

【React入门实践】复杂搜索表单的【展开-收起】功能

前端CSS面试题文档,JavaScript面试题文档,Vue面试题文档,大厂面试题文档aceholder=“总价范围” />)}})()}})(前端CSS面试题文档,JavaScript面试题文档,Vue面试题文档,大厂面试题文档[外链图片转存中…(img-r233Vysn-1718464562112)][外链图片转存中…(img-zzmWLLxB-1718464562113)]{reset}{search}{reset}{search}{reset}

2401_85124851的博客 808

2026必学:LangChain+Playwright爬虫,赋能RAG智能问答系统

RAG(检索增强生成)智能问答系统的效果,80%取决于数据源的质量。2026年,LangChain与Playwright的组合成为企业级RAG数据采集的黄金搭档:LangChain提供标准化的RAG数据处理链路,Playwright解决动态网页渲染的核心痛点,两者结合能高效采集、结构化处理各类网页数据(动态渲染页、复杂交互页、反爬页),为RAG系统提供高质量语料。

专注于Python爬虫开发,分享爬虫技巧、项目实战与反爬经验,使用Scrapy、BeautifulSoup等工具,解决数据抓取难题。 1705

Vue3中搜索表单的二次封装

经过前两步的封装之后,在使用的SearchForm组件时,简直是爽的不要不要的。{label: '项目名称', prop: 'name', type: 'input'},{label: '项目编码', prop: 'code', type: 'input'},{label: '项目描述', prop: 'desc', type: 'select', list: [{label: '未开始', value: 1}, {label: '已开始', value: 2}]},

专注前端技术,包括Web端、移动端、小程序、APP 2359

OpenCV开发笔记(〇):使用mingw530_32编译openCV3.4.1源码,搭建Qt5.9.3的openCV开发环境

欢迎技术交流和帮助,提供IT相关服务,索要源码请联系博主QQ: 21497936,若该文为原创文章,未经允许不得转载 原博主博客地址:https://blog.csdn.net/qq21497936 本文章博客地址:https://blog.csdn.net/qq21497936/article/details/79641510 目录 OpenCV开发笔记(一):使用mingw530_32编译...

长沙红胖子 Qt・西安|省级科研团队从业背景,深耕双一流体系高精尖技术配套研发|剥离高精尖机理,沉淀高端特种行业领域 Qt 工程化落地经验|博文仅分享通用技术总结,输出公开普适工程思路。 5万+

全国青少年信息素养大赛图形化(Scratch)编程考点总结

全国青少年信息素养大赛图形化(Scratch)编程考点总结

伶俐角少儿编程 382

Vue3 数据列表增删改

复制下来,粘贴在小黑窗。

m0_63359528的博客 680

Python经典编程习题100例:第25例:求各个阶乘的和

不要自卑,去提升实力 互联网行业谁技术牛谁是爹 如果文章可以带给你能量,那是最好的事!请相信自己 加油o~ 本人初学Python,只为熟悉语法编写,大神请勿理会 点击下面链接 Python经典编程100例习题汇总 题目描述: 求1+2!+3!+…+20!的和。 解题思路: > 调用math模块中的factorial函数 代码: import math sum=0 for i in range(1,21): sum+=math.factorial(i) print(sum) ..

优快云 精品推荐 2735

【亲测免费】 **探索Vue.js日志新境界 - vuejs-logger**

探索Vue.js日志新境界 - vuejs-logger 在现代Web开发中,日志记录是不可或缺的调试和监控工具,特别是在Vue.js应用开发领域。今天,我们为您隆重推荐一款专为Vue.js量身打造的日志解决方案——vuejs-logger。这款开源项目通过其高度定制化的特性,不仅简化了开发者在日常开发与维护中的日志管理,更是在提高生产环境效率的同时,保障了开发阶段的信息透明度。 项目介绍 vue...

gitblog_00053的博客 983

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain&#39;s apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath(&#39;DeepLearnToolbox&#39;));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand(&#39;state&#39;,0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W&#39;); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand(&#39;state&#39;,0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = &#39;sigm&#39;;%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, &#39;Too big error&#39;);```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand(&#39;state&#39;,0)sae = saesetup([784 100]);sae.ae{1}.activation_function = &#39;sigm&#39;;sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)&#39;)% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;;nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, &#39;Too big error&#39;);```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x&#39;,28,28,60000))/255;test_x = double(reshape(test_x&#39;,28,28,10000))/255;train_y = double(train_y&#39;);test_y = double(test_y&#39;);%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you&#39;ll get around 1.2% errorrand(&#39;state&#39;,0)cnn.layers = { struct(&#39;type&#39;, &#39;i&#39;) %input layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 6, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %sub sampling layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 12, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, &#39;Too big error&#39;);```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, &#39;Too big error&#39;);%% ex2 neural net with L2 weight decayrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex3 neural net with dropoutrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex4 neural net with sigmoid activation functionrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex5 plotting functionalityrand(&#39;state&#39;,0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = &#39;softmax&#39;; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand(&#39;state&#39;,0)nn = nnsetup([784 20 10]); nn.output = &#39;softmax&#39;; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

vue调试工具_11种顶级VueJS开发人员工具,会成为你的神兵利器吗?

全文共3283字,预计学习时长10分钟图源:Unsplash这次,小芯为大家安排上了11种顶级VueJS开发人员工具。Vue JS最近越来越流行,这主要是因为它为人们学习和开发应用程序提供了便利。无论是想要使用Vue的经验丰富的开发人员还是新手,使用正确的工具都很有必要。这将有助于快速创建出色的应用程序,而不必做重复工作。在为本文列表选取工具时,小芯考虑了整个Vue JS开发周期。从为新应用程序设...

weixin_39978749的博客 992

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

Vue3 中 Proxy 在组件封装中的妙用

本文探讨了Vue3中利用Proxy实现组件优雅交互的方法。通过Proxy的get、has、ownKeys拦截器,可以轻松透传内部组件的方法和属性,解决组件封装中的交互痛点。以DialogTable组件为例,展示了如何让父组件直接访问内部ProTable的方法,无需手动转发或暴露引用。此外还介绍了Proxy在权限控制、调用日志和默认值处理中的应用场景,并指出需要注意组件生命周期和性能考量。这种方案能显著简化接口、减少样板代码,提升组件可维护性和灵活性。

前端kk的博客 1275

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

vue3开发实践总结

这个项目也算是完整的从0到1开发一个vue3项目,虽然项目不算大,但麻雀虽小五脏俱全,该有的体验也都把玩了一下。 总体来说,vue3带来了一些新内容,但还是属于框架内的改动,无法影响到整个前端圈。如果是之前平稳运行的项目,不建议推倒重构 到vue3版本,新项目或者小项目重构,可以大胆使用vue3 vue3是vue的未来,现在也已经很成熟了,后续的新项目,都推荐使用vue3来做的...

loulanyijian的专栏 1507

Vue3不习惯的点及setup免引入便捷操作

Vue3中setup免引入(组件+属性) elementplus按需自动引入 icon自动引入的配置以及部分语法与vue2不同的点

swoly2894265391的博客 918

【Vuejs】1613- 一起玩转Vue中的 JSX

JSX简介JSX是一种Javascript的语法扩展,即具备了Javascript的全部功能,同时又兼具html的语义化和直观性。它可以让我们在JS中写模板语法:constel=<div>Vue2</div>; 复制代码上面这段代码既不是 HTML 也不是字符串,被称之为 JSX,是 JavaScript 的扩展语法。JSX 可能会使人联想到模板语法,但是它具备 J...

pingan8787 316

关于vue—cli创建vue3项目引入element plus 按需引入方式的记录

虽然说工作中一直使用的vue2 但是在空闲之余也学习学习vue3,在断断续续的学习中,打算用element框架,但是在按需引入的时候频频报错,如果不按需引入全局引入的话又导致项目体积过大,后在查阅相关资料之后顺利的解决,再次做以记录。 废话不多说直接记录 1、根据element plus 官网指引下载相关依赖 由于我用的是vue cli 不是vite所以我直接用的内部包管理器,不用内部管理器的也可以用npm 等方式引入 npm install -D unplu...

weixin_48386494的博客 922

2020年,11种应该加入工具箱的顶级VueJS开发员工具​

全文共3283字,预计学习时长10分钟 图源:Unsplash 这次,小芯为大家安排上了11种顶级VueJS开发人员工具。 Vue JS最近越来越流行,这主要是因为它为人们学习和开发应用程序提供了便利。无论是想要使用Vue的经验丰富的开发人员还是新手,使用正确的工具都很有必要。这将有助于快速创建出色的应用程序,而不必做重复工作。 在为本文列表选取工具时,小芯考虑了...

读芯术的博客 1800

前端Vue篇之Vue 3.0 中的 Vue Composition API?Composition API与React Hook很像,区别是什么

Vue 3.0 中的 Composition API 和 React Hooks 都是用于在函数式组件中管理状态和逻辑的工具,它们有相似之处,但也有一些区别。

星辰迷上大海的博客 2441

vue调试工具_2020年,11种应该加入工具箱的顶级VueJS开发员工具?

全文共3283字,预计学习时长10分钟图源:Unsplash这次,小芯为大家安排上了11种顶级VueJS开发人员工具。Vue JS最近越来越流行,这主要是因为它为人们学习和开发应用程序提供了便利。无论是想要使用Vue的经验丰富的开发人员还是新手,使用正确的工具都很有必要。这将有助于快速创建出色的应用程序,而不必做重复工作。在为本文列表选取工具时,小芯考虑了整个Vue JS开发周期。从为新应用程序设...

weixin_39542043的博客 194

vue3项目创建方式记录

vite是下一代前端开发与构建工具。Vite意在提供开箱即用的配置,同时它的插件API和JavaScript API 带来了高度的可扩展性,并有完整的类型支持。这种方式相比第二张创建方式,集成了更多依赖和工具,比如Pinia和Router,让我们开发更加便捷。

to_prototy的博客 692

html怎么连接api vue.js_2020年,11种应该加入工具箱的顶级VueJS开发员工具?

全文共3283字,预计学习时长10分钟图源:Unsplash这次,小芯为大家安排上了11种顶级VueJS开发人员工具。Vue JS最近越来越流行,这主要是因为它为人们学习和开发应用程序提供了便利。无论是想要使用Vue的经验丰富的开发人员还是新手,使用正确的工具都很有必要。这将有助于快速创建出色的应用程序,而不必做重复工作。在为本文列表选取工具时,小芯考虑了整个Vue JS开发周期。从为新应用程序设...

weixin_42679995的博客 115

Webpack从0到1搭建Vue3项目

webpack从0到1初始化Vue项目

量子前端的博客 2825
上一篇: 微信小程序踩坑记录
下一篇: 微信小程序原生组件使用
FF_XM
博客等级 码龄5年 19粉丝 44原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值