区分Vue2和Vue3的配置读取(附Demo)

前言

版本差异,此处着重做一个区分

1. 差异

读取配置时,两者版本的表示还是有些差异

Vue2的示例:

request 函数来发送 HTTP 请求,通过给定的 configKey 构建了一个 URL 来获取配置值

export function getConfigKey(configKey) {
  return request({
    url: '/xxx?key=' + configKey,
    method: 'get'
  })
}

Vue3示例:
箭头函数,使用了 Vue 3 的写法,并且使用 TypeScript 进行类型声明
通过构建 URL 来获取配置值,但是在发送请求时使用了一种不同的方式

export const getConfigKey = (configKey: string) => {
    return request.get({ url: '/xxx?key=' + configKey })
}

2. 完整示例

以下示例讲解两者使用的差异

对于后端都差不多,先给后端代码:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

@RestController
class ConfigController {

    @GetMapping("/infra/config/get-value-by-key")
    public ConfigResponse getConfigValueByKey(@RequestParam String key) {
        // 这里应该根据 key 查询相应的配置值
        String configValue = "Example Config Value";
        return new ConfigResponse(configValue);
    }
}

class ConfigResponse {

    private String value;

    public ConfigResponse() {
    }

    public ConfigResponse(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

如果采用node.js的形式,具体如下:

const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;

app.get('/xxx', (req, res) => {
  const configKey = req.query.key;
  // 这里应该根据 configKey 查询相应的配置值
  const configValue = 'Example Config Value';
  res.json({ value: configValue });
});

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

2.1 Vue2

前端如下:

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Vue 2 Example</title>
</head>
<body>
  <div id="app">
    <h1>{{ configValue }}</h1>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
  <script src="app.js"></script>
</body>
</html>
// app.js
new Vue({
  el: '#app',
  data() {
    return {
      configValue: ''
    };
  },
  mounted() {
    this.getConfigValue();
  },
  methods: {
    getConfigValue() {
      getConfigKey('example_key')
        .then(response => {
          this.configValue = response.data.value;
        })
        .catch(error => {
          console.error('Error fetching config value:', error);
        });
    }
  }
});

function getConfigKey(configKey) {
  return axios.get('/xxx?key=' + configKey);
}

2.2 Vue3

前端如下:

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Vue 3 Example</title>
</head>
<body>
  <div id="app">
    <h1>{{ configValue }}</h1>
  </div>

  <script src="https://unpkg.com/vue@next"></script>
  <script src="app.js"></script>
</body>
</html>
// app.js
const app = Vue.createApp({
  data() {
    return {
      configValue: ''
    };
  },
  mounted() {
    this.getConfigValue();
  },
  methods: {
    getConfigValue() {
      getConfigKey('example_key')
        .then(response => {
          this.configValue = response.data.value;
        })
        .catch(error => {
          console.error('Error fetching config value:', error);
        });
    }
  }
});

app.mount('#app');

async function getConfigKey(configKey) {
  const response = await fetch('/xxx?key=' + configKey);
  return await response.json();
}
  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,让我来分享一下Vue实现AWS S3分段上传的详细配置和案例demo。 首先,我们需要安装aws-sdk和vue-axios这两个依赖。在Vue项目中,我们可以使用以下命令进行安装: ``` npm install aws-sdk vue-axios --save ``` 接下来,我们需要在Vue项目的配置文件中添加AWS S3的配置信息。在这个例子中,我们假设AWS S3的Bucket名称为“mybucket”,并且我们已经创建了一个对应的IAM用户,并为其创建了访问密钥和秘钥。配置文件的示例如下: ```javascript export default { aws: { region: 'us-west-2', // AWS S3的区域 accessKeyId: 'access key id', // 访问密钥 secretAccessKey: 'secret access key', // 秘钥 bucket: 'mybucket' // S3 Bucket名称 } } ``` 接下来,我们需要创建一个Vue组件来实现AWS S3分段上传。以下是一个示例组件: ```html <template> <div> <input type="file" ref="fileInput" @change="handleFileSelect" /> <button @click="uploadFile">上传文件</button> <div>{{ uploadProgress }}</div> </div> </template> <script> import AWS from 'aws-sdk' import axios from 'vue-axios' import config from '@/config' export default { name: 'S3Uploader', data() { return { file: null, uploadId: null, parts: [], uploadProgress: 0 } }, methods: { handleFileSelect() { this.file = this.$refs.fileInput.files[0] }, async initiateMultipartUpload() { const s3 = new AWS.S3({ region: config.aws.region, accessKeyId: config.aws.accessKeyId, secretAccessKey: config.aws.secretAccessKey }) const response = await s3.createMultipartUpload({ Bucket: config.aws.bucket, Key: this.file.name }).promise() this.uploadId = response.UploadId }, async uploadPart(partNumber, partData) { const s3 = new AWS.S3({ region: config.aws.region, accessKeyId: config.aws.accessKeyId, secretAccessKey: config.aws.secretAccessKey }) const response = await s3.uploadPart({ Bucket: config.aws.bucket, Key: this.file.name, UploadId: this.uploadId, PartNumber: partNumber, Body: partData }).promise() this.parts.push({ ETag: response.ETag, PartNumber: partNumber }) }, async completeMultipartUpload() { const s3 = new AWS.S3({ region: config.aws.region, accessKeyId: config.aws.accessKeyId, secretAccessKey: config.aws.secretAccessKey }) await s3.completeMultipartUpload({ Bucket: config.aws.bucket, Key: this.file.name, UploadId: this.uploadId, MultipartUpload: { Parts: this.parts } }).promise() }, async uploadFile() { // 初始化分段上传 await this.initiateMultipartUpload() // 计算分段大小 const PART_SIZE = 1024 * 1024 * 5 // 5MB // 计算文件分段数量 const numParts = Math.ceil(this.file.size / PART_SIZE) // 创建分段上传任务 const tasks = Array.from({ length: numParts }, (v, i) => { const start = i * PART_SIZE const end = Math.min(start + PART_SIZE, this.file.size) return () => { return new Promise((resolve, reject) => { const reader = new FileReader() reader.onload = async () => { try { // 上传分段 await this.uploadPart(i + 1, reader.result) // 计算上传进度 this.uploadProgress = Math.ceil((i + 1) / numParts * 100) resolve() } catch (e) { reject(e) } } reader.readAsArrayBuffer(this.file.slice(start, end)) }) } }) // 并发执行所有上传任务 await Promise.all(tasks.map(task => task())) // 完成分段上传 await this.completeMultipartUpload() // 清空上传进度 this.uploadProgress = 0 } } } </script> ``` 上面的代码中,我们使用AWS SDK提供的“createMultipartUpload”、“uploadPart”和“completeMultipartUpload”方法来实现AWS S3分段上传。这些方法都是异步的,因此我们使用async/await语法来处理它们的返回结果。 在uploadFile方法中,我们首先调用initiateMultipartUpload方法来初始化分段上传,并获取一个上传ID。然后,我们计算文件分段数量,并为每个分段创建一个上传任务。每个上传任务都会读取相应分段的数据,并调用uploadPart方法来上传数据。上传过程中,我们会计算上传进度,并将其保存在uploadProgress变量中。最后,我们调用completeMultipartUpload方法来完成分段上传。 在模板中,我们使用一个文件输入框和一个上传按钮来触发文件上传。同时,我们使用一个div元素来显示上传进度。以下是模板代码: ```html <template> <div> <input type="file" ref="fileInput" @change="handleFileSelect" /> <button @click="uploadFile">上传文件</button> <div>{{ uploadProgress }}</div> </div> </template> ``` 最后,我们需要将S3Uploader组件注册到Vue应用程序中。这可以通过以下代码完成: ```javascript import S3Uploader from '@/components/S3Uploader' export default { name: 'App', components: { S3Uploader } } ``` 这样,我们就完成了Vue实现AWS S3分段上传的所有配置和代码。希望这个例子对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农研究僧

你的鼓励将是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值