vue3+ts实现文件读写
时间: 2023-05-25 18:04:48 浏览: 667
Vue3本身并不具备文件读写的能力,需要借助Node.js提供的fs模块来实现文件读写功能。
1. 安装Node.js
首先需要安装Node.js,可以到官方网站https://nodejs.org/ 下载安装包进行安装。
2. 创建Vue项目
在命令行中使用vue-cli创建一个Vue项目,具体命令如下:
```
vue create my-project
```
安装依赖后,进入项目目录,并安装fs模块:
```
cd my-project
npm install fs
```
3. 实现文件读写功能
在需要使用文件读写功能的地方,引入fs模块:
```
import * as fs from 'fs';
```
读取文件:
```
fs.readFile('path/to/file', (err, data) => {
if (err) throw err;
console.log(data);
});
```
其中,path/to/file是需要读取的文件路径,可以是相对路径或绝对路径。读取的结果会在回调函数中返回,如果发生错误,会抛出异常。
写入文件:
```
fs.writeFile('path/to/file', 'content', (err) => {
if (err) throw err;
console.log('File saved');
});
```
其中,content是要写入的内容。如果写入成功,会在回调函数中输出“File saved”,如果发生错误,会抛出异常。
4. 示例代码
以下是一个完整的示例代码:
```
<template>
<div>
<h1>File I/O example</h1>
<p>{{content}}</p>
<button @click="loadFile">Load file</button>
<button @click="saveFile">Save file</button>
<input v-model="newContent"/>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import * as fs from 'fs';
export default defineComponent({
data() {
return {
content: '',
newContent: ''
};
},
methods: {
loadFile() {
fs.readFile('test.txt', 'utf-8', (err, data) => {
if (err) throw err;
this.content = data;
});
},
saveFile() {
fs.writeFile('test.txt', this.newContent, (err) => {
if (err) throw err;
console.log('File saved');
});
}
}
});
</script>
```
在该示例中,可以在页面中加载一个文本文件,也可以将一个文本文件中的内容替换为用户输入的内容。启动应用后,会看到一个加载文件和保存文件的按钮,以及一个文本框用于输入新的文件内容。