<template>
<div id="app">
<h1>Vue 在线编辑器</h1>
<textarea v-model="code" placeholder="在这里输入你的代码"></textarea>
<button @click="runCode">运行</button>
<div v-html="output"></div>
</div>
</template>
<script>
export default {
data() {
return {
code: '',
output: ''
};
},
methods: {
runCode() {
try {
// 使用 new Function 来执行用户输入的代码
const result = new Function(this.code)();
this.output = typeof result === 'string' ? result : JSON.stringify(result);
} catch (error) {
this.output = `<span style="color: red;">${error}</span>`;
}
}
}
};
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
text-align: center;
margin-top: 60px;
}
textarea {
width: 80%;
height: 150px;
margin-bottom: 20px;
}
button {
padding: 10px 20px;
font-size: 16px;
}
div[v-html] {
margin-top: 20px;
white-space: pre-wrap;
}
</style>
模板部分 (<template>):
textarea 用于输入代码、一个按钮用于触发代码运行,以及一个 div 用于显示输出结果。脚本部分 (<script>):
data() 返回两个属性:code 用于存储用户输入的代码,output 用于存储代码运行后的输出结果。methods 中定义了 runCode 方法,该方法使用 new Function 来执行用户输入的代码,并将结果或错误信息显示在页面上。样式部分 (<style>):
这个示例展示了如何创建一个简单的 Vue 在线编辑器,允许用户输入 JavaScript 代码并立即查看运行结果。
上一篇:vue3 loading
下一篇:bootstrap vue3
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站