跳到主要内容

通过JSON数据获取Keys

· 阅读需 2 分钟
lzw.

请输入指定JSON格式的数据


<div>
<textarea ref="textarea" cols="30" rows="10" placeholder="JSON 数据"></textarea>
<pre><code ref="preCode"></code></pre>
</div>

<script>
import { ref,onMounted} from 'vue'
export default {
setup() {
const textarea = ref(null)
const preCode = ref(null)

// 需要在生命周期获取
onMounted(()=>{
function isJson(str) {
try {
const json = JSON.parse(str)
if (typeof json === 'object' && json) {
return true
}
return false
} catch (e) {
console.error('不是json格式的数据')
return false
}
}

// 当界面挂载出来后就会自动执行
textarea.value.addEventListener('change', function () {
let data = textarea.value.value

if (!isJson(data)) return
data = JSON.parse(data).data


//标题
const formTitle = data.title
const formSet = data.form[0].set

console.log(formTitle, formSet)

let formSetCode = `// ${formTitle}\n`
formSetCode += `const FORM_KEY = '${formSet[0].entityName}__' \n`
formSetCode += 'const formKyes = {\n'
for (let i = 0; i < formSet.length; i++) {
if (formSet[i].alias) formSetCode += ` ${formSet[i].alias}:` + ' `${FORM_KEY}' + `${formSet[i].alias}\` , //${formSet[i].title}\n`
}
formSetCode += '} \n'

let tableSetCode = ''

for (let i = 0; i < formSet.length; i++) {
if (formSet[i].typeSet.head) {
let tableTitle = formSet[i].typeSet.head[0].title
let tableSet = formSet[i].typeSet.head[0].set

console.log(tableTitle, tableSet)

tableSetCode += `// ${tableTitle} \n`
tableSetCode += `const tFORM_KEY_${tableSet[0].alias} = '${tableSet[0].entityName}__' \n`
tableSetCode += `const tFormKyes_${tableSet[0].alias} = { \n`
for (let i = 0; i < tableSet.length - 1; i++) {
if (tableSet[i].alias) tableSetCode += ` ${tableSet[i].alias}:` + ' `${tFORM_KEY_' + `${tableSet[0].alias}` + '}' + `${tableSet[i].alias}\` , //${tableSet[i].title} \n`
}
tableSetCode += '} \n'
}
}

preCode.value.innerHTML = formSetCode + tableSetCode
})
})
return {
textarea,
preCode
}
}
}
</script>

<style lang="scss" scoped>
textarea {
width: 99%;
max-height: 300px;
resize: none;
}

pre {
font-family: SFMono-Regular, Consolas, Liberation Mono, Menlo, monospace;
padding: 16px;
overflow: auto;
font-size: 85%;
line-height: 1.45;
background-color: #f6f8fa;
border-radius: 3px;
white-space: pre-wrap;

code {
color: #333;
}
}
</style>