data返回TEXTN67GH600m9kQ000012{"text:"testmsg6", "time" "20230202020202", "chatid":"N67GH100m9kQ00000y", "targets": ["KL_CS.000110"]},如何用vue拿出text、time、chatid、targets的值
时间: 2023-07-06 14:43:51 浏览: 40
可以先将返回的字符串解析为JSON对象,然后使用Vue的数据绑定(data binding)功能将解析后的值绑定到对应的变量上。具体的代码示例如下:
```vue
<template>
<div>
<div>{{ message.text }}</div>
<div>{{ message.time }}</div>
<div>{{ message.chatid }}</div>
<div v-for="(target, index) in message.targets" :key="index">{{ target }}</div>
</div>
</template>
<script>
export default {
data() {
return {
message: {
text: "",
time: "",
chatid: "",
targets: []
}
};
},
mounted() {
// 假设返回的字符串被存储在response变量中
const response = 'TEXTN67GH600m9kQ000012{"text":"testmsg6","time":"20230202020202","chatid":"N67GH100m9kQ00000y","targets":["KL_CS.000110"]}';
// 将字符串解析为JSON对象
const data = JSON.parse(response.substring(4));
// 将解析后的值绑定到message变量上
this.message.text = data.text;
this.message.time = data.time;
this.message.chatid = data.chatid;
this.message.targets = data.targets;
}
};
</script>
```
在上面的代码中,我们首先在`data`函数中定义了一个`message`变量,它包含了`text`、`time`、`chatid`和`targets`四个属性。在`mounted`生命周期钩子函数中,我们首先使用`substring`方法将返回的字符串中的前缀("TEXT"和房间号)去掉,然后使用`JSON.parse`方法将剩余部分解析为JSON对象。最后,我们将解析后的值分别赋给`message`变量中对应的属性,从而实现了将数据绑定到视图上的效果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)