uni-app 使用笔记

发布于:2024-12-07 ⋅ 阅读:(188) ⋅ 点赞:(0)

1.缓存用法

(1)uni-app 存值+取值+删除

官网:https://uniapp.dcloud.net.cn/api/storage/storage.html#setstorage
存值

uni.setStorageSync('storage_key', 'hello');

取值

uni.getStorageSync('storage_key')

删除

uni.removeStorageSync('storage_key')

2.列表左侧点击访问详情,右侧点击处理业务

(1)效果

在这里插入图片描述

(2)代码

<template>
  <uni-list>
  	<uni-list-item v-for="item in hospitalJobRequireList" :title="item.hosName" :note="item.jobName" clickable @click="onClick(item)">
      <template v-slot:footer v-if="item.isGw=='N'">
        <button style="height: 45px;width: 100px;" class="uni-icon yticon icon-shanchu" @click.stop="rightClick(item)">岗位申请</button>
      </template>
    </uni-list-item>
  </uni-list>
</template>

<script>
import {applyList} from "@/api/expertVeteran/hospital";

export default {
  data() {
    return {
      hospitalJobRequireList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        hospitalId: null,
        jobName: null,
        num: null,
        description: null,
        professionalRequire: null,
        eduRequire: null,
        postRequire: null,
        salary: null,
        contact: null,
        phone: null,
        email: null,
        workLocation: null,
        status: null,
        sort: null,
      },
    }
  },
  created(){
    this.getList();
  },
  methods:{
    /** 查询医院岗位需求列表 */
    getList() {
      this.$modal.loading("数据加载中...")
      applyList(this.queryParams).then(response => {
        console.log(response)
        this.hospitalJobRequireList = response.rows;
        this.$modal.closeLoading();
      });
    },
    onClick(data){
       this.$tab.navigateTo(`/pages/expertVeteran/hospital/job/detail?id=${data.id}`)
    },
    rightClick(){
      this.$modal.showToast('点击右侧按钮调用')
    }
  }
}
</script>

<style>
/* 样式按需添加 */
.uni-icon {
  margin-right: 10px; /* 调整右侧图标与文字的间隔 */
}
</style>

参考:
https://uniapp.dcloud.net.cn/component/uniui/uni-list.html#listitem-slots
百度ai
在这里插入图片描述在这里插入图片描述

3.动态设置页面标题(NavigationBarTitle)

onLoad(event) {
  uni.setNavigationBarTitle({
    title:'顶顶顶顶顶'
  });
  this.getInfo(event.id)
},

4.列表下拉刷新,下拉加载

<template>
  <uni-list>
  	<uni-list-item v-for="item in hospitalJobRequireList" :title="item.hosName" :note="item.jobName" clickable @click="onClick(item)">
      <template v-slot:footer v-if="item.isGw=='N'">
        <button style="height: 45px;width: 100px;" class="uni-icon yticon icon-shanchu" @click.stop="onClick(item)">岗位申请</button>
      </template>
    </uni-list-item>
    <uni-load-more :status="status" @clickLoadMore="loadMore"></uni-load-more>
  </uni-list>
</template>

<script>
import {applyList} from "@/api/expertVeteran/hospital";

export default {
  data() {
    return {
      hospitalJobRequireList: [],
      total:0,
      status:'more',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
    }
  },
  created(){
    this.getList();
  },
  //下拉刷新
  onPullDownRefresh() {
    this.hospitalJobRequireList=[];
    this.queryParams.pageNum=1;
    this.queryParams.pageSize=10;
    this.status='more';
    this.getList();
    setTimeout(function() {
      uni.stopPullDownRefresh();
    }, 1000);
  },

  methods:{
    /** 查询医院岗位需求列表 */
    getList() {
      this.$modal.loading("数据加载中...")
      applyList(this.queryParams).then(response => {
        this.hospitalJobRequireList=this.hospitalJobRequireList.concat(response.rows);
        this.total = response.total;
        if (this.hospitalJobRequireList.length>=this.total){
            this.status='noMore';
        }
        this.$modal.closeLoading();
      });
    },
    onClick(data){
       this.$tab.navigateTo(`/pages/expertVeteran/hospital/job/detail?id=${data.id}`)
    },

    loadMore(){
      if (this.status=='more'){
        this.queryParams.pageNum++;
        this.getList();
      }
    },
  }
}
</script>

<style>
/* 样式按需添加 */
.uni-icon {
  margin-right: 10px; /* 调整右侧图标与文字的间隔 */
}
</style>

5.需要动态更新的值,赋值没有生效的可能原因

(1)先定义一下需要赋值的字段

比如 要动态改变:form.code 中code的值,先提前定义一下

export default {
	data() {
		return {
			// 基础表单数据
			form: {code:null},
		}
	}
}

6.获取config.js 里面的所有内容

export default {
  data() {
    return {
     globalConfig: getApp().globalData.config,
    }
  },
}

7.文件上传下载组件

在这里插入图片描述

(1) 新建组件:components=>fileUpload.vue

<template>
	<view>
		<button class="file-upload-button" @click="chooseFile">选择文件</button>
    <input :value="value" type="text" style="display:none"/>
		<view v-for="(file,index) in fileList">
			<view>
				<view style="float: left;">
          {{file.fileName}}
        </view>
				<view style="color: red;float: left;margin-left: 10px;" @click="delFile(index)">
					删除
				</view>
        <view @click="download(file.url)" style="color: blue;float: left;margin-left: 15px;">
          下载
        </view>
			</view>
		</view>
	</view>
</template>

<script>
	import config from '@/config'
  import {getFileName} from '@/utils/str'

	const baseUrl = config.baseUrl
	export default {
    props: ['value'],
    watch: {
      //监听value
      value(val){
        this.fileList.push({url:val,fileName:getFileName(val)})
      }
    },
		data() {
			return {
				file: null,
				fileList:[]
			};
		},
		methods: {
			//删除文件
			delFile(index){
				this.fileList.splice(index,1);
			},
			
			chooseFile() {
				uni.chooseFile({
					success: (res) => {
						this.file = res.tempFiles[0];
						this.uploadFile();
					},
					fail: (err) => {
						console.log('选择文件失败', err);
					},
				});
			},
			uploadFile() {
				if(this.fileList.length>0){
					this.$modal.showToast("只能上传一个文件");
					return;
				}
				if (this.file) {
					const uploadTask = uni.uploadFile({
						url: baseUrl + '/api/common/file/upload', // 替换为你的上传地址
						filePath: this.file.path,
						name: 'file', // 这里根据服务器要求修改
						header: {
							Authorization: 'Bearer ' + this.$store.state.user.token
						},
						formData: {
							// 这里可以添加其他要上传的表单字段
						},
						success: (uploadRes) => {
               let data=JSON.parse(uploadRes.data).data;
							 this.$emit('input',data.fileName);
						},
						fail: (uploadErr) => {
							console.log('上传失败', uploadErr);
						},
					});
					uploadTask.onProgressUpdate((res) => {
						console.log('上传进度', res.progress);
					});
				}
			},

      //签订合同下载
      download(file) {
        //下载文档
        uni.downloadFile({
          url: baseUrl + '/api/common/file/download?fileName='+file,//下载地址接口返回
          header: {
            Authorization: 'Bearer ' + this.$store.state.user.token
          },
          success: (data) => {
            if (data.statusCode === 200) {
              /*#ifdef H5*/
              const a = document.createElement('a');
              a.href = data.tempFilePath;
              a.download = "robots.txt"; // 可以设置下载文件名,如果是空字符串,则使用服务器端设置的文件名
              a.click();
              /*#ifdef H5*/

              /*#ifdef MP-WEIXIN*/
              //文件保存到本地
              uni.saveFile({
                tempFilePath: data.tempFilePath, //临时路径
                success: function(res) {
                  uni.showToast({
                    icon: 'none',
                    mask: true,
                    title: '文件已保存:' + res.savedFilePath, //保存路径
                    duration: 3000,
                  });
                  setTimeout(() => {
                    //打开文档查看
                    uni.openDocument({
                      filePath: res.savedFilePath,
                      success: function(res) {
                        // console.log('打开文档成功');
                      }
                    });
                  }, 3000)
                }
              });
              /*#endif*/
            }
          },
          fail: (err) => {
            console.log(err);
            uni.showToast({
              icon: 'none',
              mask: true,
              title: '失败请重新下载',
            });
          },
        });
      },
		},
	};
</script>

<style>
	.file-upload-button {
		display: inline-block;
		cursor: pointer;
		border: none;
		outline: none;
		color: #fff;
		background-color: #007bff;
		padding: 0px 10px;
		border-radius: 5px;
		font-size: 14px;
	}
</style>

(2)使用

<template>
	<fileUpload v-model="baseFormData.priorRet"></fileUpload>
</template>
<script>
import fileUpload from '@/components/fileUpload.vue'
export default {
	components: {
		fileUpload
	},
}
</script>

(3)其他相关

utils=>str.js

//下载文件 返回文件名及后缀
export function getFileName(fileUrl) {
    var startIndex = fileUrl.lastIndexOf("/");
    var endIndex = fileUrl.lastIndexOf("_");

    var fileName=fileUrl.substring(startIndex+1,endIndex);
    var suffix = fileUrl.substring(fileUrl.lastIndexOf("."));//文件后缀
    return fileName+suffix;
}