2024-08-15



// 导入NAPI的API
const {
    napi_create_function,
    napi_get_cb_info,
    napi_call_function,
    napi_get_value_string_utf8,
    napi_create_string_utf8,
    napi_get_null,
    napi_set_named_property,
    napi_get_global,
    napi_create_object,
} = require('node-addon-api');
 
// 导出函数
module.exports = {
    registerHelloWorld: registerHelloWorld
};
 
// 注册函数
function registerHelloWorld(env, exports) {
    // 创建一个新的函数
    const helloWorld = napi_create_function(env, null, (env, info) => {
        // 获取回调信息
        let argc = 0;
        let argv = null;
        let thisVar = null;
        napi_get_cb_info(env, info, argc, argv, thisVar, null);
 
        // 获取参数并转为字符串
        let arg = napi_get_value_string_utf8(env, argv[0], null);
 
        // 创建一个字符串
        let greeting = napi_create_string_utf8(env, `Hello, ${arg}!`);
 
        // 返回结果
        return greeting;
    });
 
    // 将函数设置为exports的属性
    napi_set_named_property(env, exports, 'helloWorld', helloWorld);
}

这段代码演示了如何使用NAPI创建一个简单的函数,并将其导出,以便在JavaScript中使用。它展示了如何获取参数、调用函数和创建字符串,以及如何将其作为属性添加到全局对象中。这是学习OpenHarmony JS/ArkTS编程的一个很好的起点。

2024-08-15

在uni-app中,可以通过全局配置或页面配置来自定义导航栏。以下是一个简单的示例,展示如何在uni-app中自定义导航栏:

  1. 全局配置自定义导航栏:

App.vue 中,可以使用 globalStyle 配置全局样式,包括导航栏的样式。




// App.vue
export default {
  globalStyle: {
    navigationBarBackgroundColor: '#FFFFFF', // 导航栏背景颜色
    navigationBarTextStyle: 'black', // 导航栏标题颜色,black / white
    navigationBarTitleText: '自定义导航栏', // 导航栏标题文字
  }
}
  1. 页面配置自定义导航栏:

在页面的配置文件中(.vue 文件中的 <script> 标签内),使用 navigationStyle 设置导航栏样式,并可以自定义标题。




// 页面配置示例
export default {
  navigationBarTitleText: '页面自定义标题',
  navigationStyle: 'custom' // 开启自定义导航栏
}
  1. 自定义导航栏的样式和内容:

在页面的 .vue 文件中,使用 <navigation-bar> 组件来自定义导航栏的样式和内容。




<!-- 页面文件中 -->
<template>
  <view>
    <navigation-bar title="自定义标题" backgroundColor="#333333" frontColor="#FFFFFF">
      <!-- 这里可以放置自定义的左右按钮 -->
    </navigation-bar>
    <!-- 页面的其他内容 -->
  </view>
</template>
 
<script>
// 导入自定义导航组件
import navigationBar from '@/components/navigation-bar.vue';
 
export default {
  components: {
    navigationBar
  }
}
</script>
  1. 创建自定义导航组件:

components 目录下创建 navigation-bar.vue 文件,定义自定义导航组件的样式和逻辑。




<!-- navigation-bar.vue -->
<template>
  <view class="navigation-bar" :style="{ backgroundColor: backgroundColor }">
    <!-- 导航栏的标题和按钮 -->
    <text class="navigation-bar-title" :style="{ color: frontColor }">{{ title }}</text>
  </view>
</template>
 
<script>
export default {
  props: {
    title: {
      type: String,
      default: ''
    },
    backgroundColor: {
      type: String,
      default: '#FFFFFF'
    },
    frontColor: {
      type: String,
      default: '#000000'
    }
  }
}
</script>
 
<style>
.navigation-bar {
  /* 自定义样式 */
}
.navigation-bar-title {
  /* 标题样式 */
}
</style>

通过以上步骤,你可以为uni-app应用创建自定义的导航栏。记得在页面配置中将 navigationStyle 设置为 custom 来开启自定义导航栏,并在页面中引入和使用自定义导航组件。

2024-08-15

这是一个使用Express框架创建简单的RESTful API的示例代码。




const express = require('express');
const app = express();
const port = 3000;
 
// 中间件,用于解析JSON格式的请求体
app.use(express.json());
 
// 用户列表
const users = [];
 
// 用户API路由
app.get('/users', (req, res) => {
  res.send(users);
});
 
app.post('/users', (req, res) => {
  const newUser = {
    id: users.length + 1,
    name: req.body.name,
    email: req.body.email
  };
  users.push(newUser);
  res.status(201).send(newUser);
});
 
// 启动服务器
app.listen(port, () => {
  console.log(`服务器运行在 http://localhost:${port}`);
});

这段代码首先导入了Express,并初始化了一个简单的应用。定义了一个用户列表,并实现了两个API端点:一个用于获取用户列表,另一个用于创建新用户。创建新用户时,为用户分配了一个唯一的ID,并将其加入到用户列表中。最后,应用监听在指定的端口上的入站连接。

2024-08-15

在这个教程中,我们将使用Vue 3、Vite和JavaScript来创建一个可以打包成Electron桌面应用程序的Web项目。

  1. 创建一个Vue 3项目:



npm create vue@latest
# 然后按照提示进行操作,选择Vue 3和使用Vite
  1. 安装Electron依赖:



npm install electron --save-dev
  1. 在项目根目录下创建一个electron-builder.yml配置文件,用于Electron的构建配置:



# electron-builder.yml
directories:
  output: build
  buildResources: buildResources
files:
  extra:
    - README.md
    - LICENSE
    - .electron-vue/electron.js
    - build/icons/*
asar: true
  1. package.json中添加Electron的脚本:



{
  "scripts": {
    "electron:build": "vue-tsc --noEmit && vite build",
    "electron:dev": "vue-tsc --noEmit && electron .",
    "electron:pack": "vue-tsc --noEmit && vite build && electron-builder --dir",
    "electron:dist": "vue-tsc --noEmit && vite build && electron-builder"
  }
}
  1. 创建Electron的主进程文件.electron-vue/electron.js



const { app, BrowserWindow } = require('electron')
const path = require('path')
 
function createWindow () {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true
    }
  })
 
  win.loadURL('http://localhost:3000')
  // 如果你想要加载打包后的web应用,可以使用:
  // win.loadFile('dist/index.html')
}
 
app.whenReady().then(createWindow)
  1. 创建预加载脚本.electron-vue/preload.js(可选,根据需要使用):



// 你可以在这里做一些Electron的预加载工作,例如:
// const { contextBridge, ipcRenderer } = require('electron')
  1. 最后,运行以下命令来启动Electron应用:



npm run electron:dev

这个教程提供了一个基本框架来将Web项目打包成Electron桌面应用程序。根据你的具体需求,你可能需要进一步配置Electron的主进程和预加载脚本。

2024-08-15

一种实现方法是使用字符串的截取函数substring

获取指定字符后面的所有字符串:




function getStringAfter(str, char) {
  var index = str.indexOf(char);
  if (index === -1) return "";  // 如果未找到指定字符,则返回空字符串
  return str.substring(index + char.length);
}
 
// 示例用法
var result = getStringAfter("Hello, world", ",");
console.log(result);  // 输出: " world"

获取指定字符前面的所有字符串:




function getStringBefore(str, char) {
  var index = str.indexOf(char);
  if (index === -1) return "";  // 如果未找到指定字符,则返回空字符串
  return str.substring(0, index);
}
 
// 示例用法
var result = getStringBefore("Hello, world", ",");
console.log(result);  // 输出: "Hello"

另一种实现方法是使用字符串的分割函数split

获取指定字符后面的所有字符串:




function getStringAfter(str, char) {
  var parts = str.split(char);
  return parts.slice(1).join(char);
}
 
// 示例用法
var result = getStringAfter("Hello, world", ",");
console.log(result);  // 输出: " world"

获取指定字符前面的所有字符串:




function getStringBefore(str, char) {
  var parts = str.split(char);
  return parts[0];
}
 
// 示例用法
var result = getStringBefore("Hello, world", ",");
console.log(result);  // 输出: "Hello"
2024-08-15



(function flexible(window, document) {
  var docEl = document.documentElement;
  var dpr = window.devicePixelRatio || 1;
  // adjust body font size
  function setBodyFontSize() {
    if (document.body) {
      document.body.style.fontSize = 12 * dpr + 'px';
    }
    else {
      document.addEventListener('DOMContentLoaded', setBodyFontSize);
    }
  }
  setBodyFontSize();
 
  // set 1rem = viewWidth / 10
  function setRemUnit() {
    var rem = docEl.clientWidth / 10;
    docEl.style.fontSize = rem + 'px';
  }
 
  setRemUnit();
 
  // reset rem unit on page resize
  window.addEventListener('resize', setRemUnit);
  window.addEventListener('pageshow', function(e) {
    if (e.persisted) {
      setRemUnit();
    }
  });
 
  // detect 0.5px supports
  if (dpr >= 2) {
    var fakeBody = document.createElement('body');
    var testElement = document.createElement('div');
    testElement.style.border = '.5px solid transparent';
    fakeBody.appendChild(testElement);
    docEl.appendChild(fakeBody);
    if (testElement.offsetHeight === 1) {
      docEl.classList.add('hairlines');
    }
    docEl.removeChild(fakeBody);
  }
}(window, document));

这段代码实现了移动端页面的自适应布局,通过设置document.body.style.fontSizedocument.documentElement.style.fontSize来分别定义了不同元素的基础字体大小。其中,document.documentElement指的是文档根元素,在HTML中通常是<html>标签。通过监听窗口大小变化,代码能够实时调整基础字体大小,从而实现响应式布局。

2024-08-15

在JavaScript中,可以使用Object.keys(), Object.values(), 或 Object.entries()方法将对象转换为数组。

  1. Object.keys(obj): 返回一个包含对象所有自有可枚举属性名称的数组,属性名以字符串形式返回。



const obj = { a: 1, b: 2, c: 3 };
const keys = Object.keys(obj); // ["a", "b", "c"]
  1. Object.values(obj): 返回一个包含对象所有自有可枚举属性值的数组。



const obj = { a: 1, b: 2, c: 3 };
const values = Object.values(obj); // [1, 2, 3]
  1. Object.entries(obj): 返回一个包含对象所有自有可枚举属性的键值对数组。



const obj = { a: 1, b: 2, c: 3 };
const entries = Object.entries(obj); // [["a", 1], ["b", 2], ["c", 3]]

以上方法返回的数组可以用于进一步的操作,例如遍历、映射或过滤。

2024-08-15

在HTML5、CSS3和JavaScript的基础上,创建一个简单的网页,该网页包含一个按钮,点击后在控制台输出"Hello, World!"。




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript Example</title>
    <style>
        button {
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
    </style>
</head>
<body>
 
<button onclick="sayHello()">Click Me</button>
 
<script>
    function sayHello() {
        console.log('Hello, World!');
    }
</script>
 
</body>
</html>

这个简单的网页展示了如何在HTML中添加一个按钮,并在CSS中给它一个样式。JavaScript函数sayHello()被绑定到按钮的点击事件上,当按钮被点击时,它会在浏览器的控制台输出"Hello, World!"。

2024-08-15



<template>
  <view class="container">
    <canvas canvas-id="canvas" style="width: 100%; height: 100%"></canvas>
  </view>
</template>
 
<script>
  import * as THREE from 'three';
  import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
 
  export default {
    data() {
      return {
        camera: null,
        scene: null,
        renderer: null,
        model: null
      }
    },
    onReady() {
      this.initThree();
      this.addLights();
      this.addCamera();
      this.loadModel();
      this.animate();
    },
    methods: {
      initThree() {
        this.scene = new THREE.Scene();
        this.renderer = new THREE.WebGLRenderer({ antialias: true });
        this.renderer.setSize(uni.upx2px(750), uni.upx2px(750));
        uni.createSelectorQuery()
          .select('#canvas')
          .node()
          .then(res => {
            res.appendChild(this.renderer.domElement);
          });
      },
      addLights() {
        const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
        this.scene.add(ambientLight);
        const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
        directionalLight.position.set(1, 1, 1);
        this.scene.add(directionalLight);
      },
      addCamera() {
        this.camera = new THREE.PerspectiveCamera(75, 1, 0.1, 1000);
        this.camera.position.set(0, 10, 20);
        this.camera.lookAt(0, 0, 0);
      },
      loadModel() {
        const loader = new GLTFLoader();
        loader.load('path/to/your/model.glb', (gltf) => {
          this.model = gltf.scene;
          this.scene.add(this.model);
        }, undefined, (error) => {
          console.error(error);
        });
      },
      animate() {
        requestAnimationFrame(this.animate);
        this.model.rotation.y += 0.01;
        this.renderer.render(this.scene, this.camera);
      }
    }
  }
</script>
 
<style>
  .container {
    width: 750rpx;
    height: 750rpx;
    background-color: #000;
  }
</style>

这段代码展示了如何在UniApp中初始化Three.js,添加灯光、相机和3D模型,并使用GLTFLoader加载一个3D模型。在onReady生命周期钩子中,它设置了Three.js的场景、渲染器,并将渲染器挂载到Canvas上。然后,它添加了环境光和平行光,并设置了相机的位

2024-08-15

要在IntelliJ IDEA中将后端Java代码打包成jar,并且将前端Vue代码通过Nginx进行部署,你可以分别进行以下步骤:

  1. 后端Java代码打包为jar:

    • 在IntelliJ IDEA中,打开Build菜单,选择Build Artifacts,然后选择Build或者Rebuild来生成jar文件。
    • 配置Artifacts:在Project Structure -> Artifacts中设置,确保包含了所有需要的依赖和类文件。
  2. 前端Vue代码打包并部署:

    • 在Vue项目目录下运行npm run build来生成生产环境下的可部署文件。
    • 将构建好的dist目录下的文件上传到服务器的Nginx可以访问的目录。
    • 配置Nginx服务器,在nginx.conf中设置正确的server块,包括静态资源的location块,并指向Vue构建的静态文件目录。

以下是简化的Nginx配置示例:




server {
    listen 80;
    server_name your-domain.com; # 你的域名或IP
 
    location / {
        root /path/to/vue/dist; # Vue构建后的文件目录
        try_files $uri $uri/ /index.html;
    }
 
    # 如果你的后端服务也在同一台服务器上,并且通过API访问
    location /api/ {
        proxy_pass http://localhost:8080; # 假设你的Java后端运行在8080端口
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

确保替换your-domain.com, /path/to/vue/dist, http://localhost:8080为实际值。

最后,确保Nginx配置正确无误,并重启Nginx服务。当你通过浏览器访问指定的域名时,Nginx将会提供Vue构建的静态文件,并通过配置的/api/路径代理请求到后端Java服务。