0
点赞
收藏
分享

微信扫一扫

蓝桥杯 题库 简单 每日十题 day6

非衣所思 2023-09-21 阅读 25

在 Vue 3 中,你可以创建一个组件,让用户输入 JSON,并将这个 JSON 渲染成某种样式或结构。以下是一个简单示例,它涵盖了如何在 Vue 3 中创建一个接受 JSON 输入并呈现其内容的组件:

  1. Setup Vue Project:
    如果你还没有设置 Vue 3 项目,可以使用 Vue CLI 进行设置:

    npm install -g @vue/cli
    vue create my-vue3-project
    

    然后选择 Vue 3 配置。

  2. 创建 JSON 输入组件:

JsonInputComponent.vue

<template>
  <div>
    <textarea v-model="jsonInput" @input="parseJson" placeholder="Enter JSON here"></textarea>
    <div v-if="parsedData">
      <pre>{{ parsedData }}</pre>
    </div>
    <p v-if="error" style="color: red;">{{ error }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      jsonInput: '',
      parsedData: null,
      error: null
    };
  },
  methods: {
    parseJson() {
      try {
        this.parsedData = JSON.parse(this.jsonInput);
        this.error = null;
      } catch (e) {
        this.parsedData = null;
        this.error = 'Invalid JSON!';
      }
    }
  }
};
</script>

<style scoped>
/* Add your CSS styling here */
textarea {
  width: 100%;
  height: 200px;
}
</style>
  1. 使用组件:

在你的主文件或任何父组件中,你可以如下使用 JsonInputComponent:

<template>
  <div>
    <JsonInputComponent />
  </div>
</template>

<script>
import JsonInputComponent from './path-to/JsonInputComponent.vue';

export default {
  components: {
    JsonInputComponent
  }
};
</script>

这个示例仅仅展示了如何解析和显示输入的 JSON。你可以根据需要对该 JSON 进行任何形式的呈现或操作。

举报

相关推荐

0 条评论