【Uniapp】开发问题篇

253 阅读3分钟

1. 打开pdf地址的方法

在 uni-app 中打开 PDF 地址可以通过使用 uni.navigateTo 或 uni.redirectTo 方法结合 vue-pdf-signature 组件来实现。以下是实现步骤:

实现步骤

1. 创建包含 vue-pdf-signature 组件的页面

<template >
  <view >
    <movable-area class="area-wrapper">
      <movable-view class="area-view" :scale="true"
       direction="all" 
       :x="x" 
       :y="y"
       :scale-min="0.2"
       :style="customStyle2"
       inertia
      >
      <view>
        <pdf  :src="pdfUrl" :page="i" :rotate="0" v-for="i in numPages" :key="i" :ref="'pdf'+i" />
      </view>
      </movable-view>
    </movable-area>
    </view>
</template>
<script>
import CMapReaderFactory from "vue-pdf-signature/src/CMapReaderFactory";
import pdf from "vue-pdf-signature";
  export default {
    data() {
      return {
        pdfUrl: null,
        numPages: 0,
        x: 10,
        y: 10,
        customStyle2: {
          width: '100vw',
          height: '100vh'
        },
      }
    },
    components: {
      pdf,
  },

  onLoad(option) {
      const pdfUrl = JSON.parse(decodeURIComponent(option.pdfUrl));
      this.pdfUrl = pdf.createLoadingTask({ 
          url: pdfUrl,
          cMapPacked: true,
          CMapReaderFactory, 
      });
    this.getNumPages();
    // 处理pdf 加载完高度才能获取真实高度,使用定时器临时处理
    setTimeout(() => {
      this.getPDFHeight()
    },1000)
  },
  methods: {
    getNumPages() {
      this.pdfUrl.promise.then(pdf => {
        this.numPages = pdf.numPages;
      }).catch(err => {
        console.error('pdf 加载失败', err);
      })
    }, 
    getPDFHeight() {
      let pdfS = Object.keys(this.$refs).map(item => {
        return this.$refs[item][0].$el.offsetHeight
      })
      this.customStyle2.height = pdfS.reduce((a,b) => {
        return a+b
      }, 0) + 'px'
    }
  }
}
</script>

<style lang="scss" scoped>
  .area-wrapper{
    width:100%;
    height:100vh;
  }
  .area-view{
    width:100vw;
    height:100vh;
  }
</style>

2. 使用路由跳转方法打开 PDF 页面

在需要打开 PDF 的地方,使用 uni.navigateTo 或 uni.redirectTo 方法跳转vue-pdf-signature页面,并传递 PDF 地址参数。

uni.navigateTo({
  url: '/pages/pdfViewer/pdfViewer?pdfUrl=' + encodeURIComponent('https://uat.com/pdf.pdf'),
});

2. 实现文字超过宽度显示按钮,否则隐藏按钮

获取设备宽度

export default {
  data() {
    return {
      screenWidth: 0,
    };
  },
  async beforeRouteEnter(to, from, next) {
    // 在路由守卫中获取
    const screenWidth = await this.getScreenWidth(); // 调用获取屏幕宽度的方法
    next(vm => {
      vm.screenWidth = screenWidth;
    });
  },
  methods: {
    // 获取屏幕宽度的方法
    getScreenWidth() {
      return new Promise((resolve) => {
        uni.getSystemInfo({
          success: (res) => {
            resolve(res.screenWidth);
          },
          fail: (error) => {
            console.error('获取屏幕宽度失败:', error);
            resolve(0); // 返回默认值或者处理失败情况
          }
        });
      });
    }
  }
}

获取文字宽度

<template>
  <view>
    <text>文本宽度测量示例</text>
    <button @click="measureTextWidth">测量文本宽度</button>
    <text>文本宽度: {{ textWidth }} px</text>
    <canvas id="myCanvas" canvas-id="myCanvas" style="display:none;"></canvas>
  </view>
</template>

<script>
export default {
  data() {
    return {
      text: '这是一个测试文本',
      textWidth: 0
    };
  },
  methods: {
    measureTextWidth() {
      // 创建 canvas 上下文
      const context = uni.createCanvasContext('myCanvas', this);
      context.setFontSize(16);  // 设置字体大小,确保与实际使用的字体大小一致
      context.setFontFamily('Arial');
      context.setFontWeight('bold');

      // 测量文本宽度
      context.measureText(this.text, (res) => {
        this.textWidth = res.width;
        console.log('文本宽度:', this.textWidth);
      });
    }
  }
};
</script>

按钮显示控制

export default {
  data() {
    return {
      buttonVisible: false // 初始状态下隐藏按钮
    };
  },
  mounted() {
    this.checkTextWidth();
  },
  methods: {
    checkTextWidth() {
      let contentWidth = this.screenWidth - 60; 
      let textWidth = this.textWidth;

      if (textWidth > contentWidth) {
        this.buttonVisible = true;
      } else {
        this.buttonVisible = false;
      }
    }
  }
};

3. 单站点部署针对 static 等静态资源访问

单站点配置文件[manifest.json]

"h5" : {
    "title" : "--------",
    "router" : {
        "mode" : "hash",
        "base" : "/" 
    },
    "publicPath" : "/"  // 注意是 yarn build:h5 才会使用这个路径
}

单站点访问

  • 比如: 我们设置的域名为: https://h5.example.com 访问的路径是我们打包后的 dist/build/h5/index.html
  • 这种情况我们 配置文件设置成 "base : "/", 同时 "publicPath": "/"

多站点配置文件

"h5" : {
    "title" : "物业公告",
    "router" : {
        "mode" : "hash",
        "base" : "/notice/"  此处填写当前sub-path 对应的路径  此处可改成 pay or notice or word
    },
    "publicPath" : "./"  此处注意一点, 需要设置成 `./` 此处用于生成index.html 引用JS文件位置
}

4. uni-app 弹框弹窗滚动、滑动页面穿透

弹框最外层禁用滚动

弹框最外层使用@touchmove.stop.prevent="preventHandler" 屏蔽触摸事件,屏蔽后如果弹框内还有列表,则列表此时无法滚动。

<template>
    <view @touchmove.stop.prevent="preventHandler"></view>
</template>

<script>
    export default {
        methods: {
            // 禁止滑动
            preventHandler() {
                return
            }
        }
    }
</script>

弹出内部滚动

如果弹框内部还有滚动列表,则可以使用 scroll-view,并设置scroll-y="true" scroll-view 不会受到@touchmove.stop.prevent="preventHandler" 的影响。

<template>
    <view @touchmove.stop.prevent="preventHandler">
        <scroll-view scroll-y="true"></scroll-view>
    </view>
</template>