Vue3 响应式全局对象json 动态绑定界面五 ( v-for 和 v-if 的应用)
效果图
man.js
定义 响应式全局对象 globalData
定义一个没有具体参数的json象 extTelTalkData: [], 这么写的好处是 事先不写具体参数,赋值时实例就行。
我是用websocket 收到消息 并赋值的,当然也可以用其它方式赋值。
//全局对象
const globalData=reactive({
extTelTalkData: [],
})
app.provide('globalData', globalData);
websocket 收到消息 并赋值 的示例
//分析websocket收到的消息
function websocket_resMsg(msg){
console.log('收到的消息 '+ msg);
let length = msg.length; //消息的长度
if(length>=12){
var msgStatusType= msg.substr(0, 10);//取得消息头,判断消息类型
if(msgStatusType=="ExtTelTalk"){
//分机 通话div
websocket_resMsg_extTelTalk(msg);
return;
}else if(msgStatusType=="ExtTelList"){
//分机列表
websocket_resMsg_extTelListData(msg);
return;
}
}
}
//收到 ExtTelTalk 消息的处理
function websocket_resMsg_extTelTalk(msg){
var msgExtTelTalk= msg.substr(10);//去掉消息头
//globalData.extTelMonitorData=JSON.parse(msgExtTelStatus); //严格的json转换
//将字符串转为json对象
globalData.extTelTalkData=eval('('+msgExtTelTalk+')');//非严格
console.log('收到分机 通话状态 '+ globalData.extTelTalkData);
}
websocket消息格式的示例
其中ExtTelTalk 用于判断消息类型的,需要截取,剩下的是 需要使用的 json数据
ExtTelTalk[{
"uuid":"7e0d50b9-b130-48f5-b57f-ae4e95399d5c",
"direction":"inbound",
"created":"2023-08-22 12:02:46",
"cid_num":"1003",
"dest":"1001",
"callstate":"EARLY"},
{"uuid":"c1a2951a-21d0-4d21-b155-9e7c453aadb5",
"direction":"outbound",
"created":"2023-08-22 12:02:46",
"cid_num":"1003",
"dest":"1001",
"callstate":"RINGING"
}]
RightSideComponent.vue 模板页
<span v-if="dataItem.callstate == 'EARLY'" >回铃</span> 其中 v-if 的条件如果为 false 则 这个<span> 不会显示
<li class="">
<a href="javascript:;" class="IndRea flexC Huans"><i></i><p>当前通话 [ {{ globalData.extTelTalkData.length }} ]</p></a>
<div class="IndReN" >
<div class="dataFontStyle">
<el-row :gutter="74" v-for="(dataItem, index) in globalData.extTelTalkData" :key="index">
<el-col :span="8" class="dataFontStyle" v-if="dataItem.direction == 'outbound'">
{{dataItem.dest}}
<span v-if="dataItem.callstate == 'EARLY'" >回铃</span>
<span v-if="dataItem.callstate == 'RINGING'" >振铃</span>
<span v-if="dataItem.callstate == 'ACTIVE'" >通话</span>
{{dataItem.cid_num}}
</el-col>
<el-col :span="8" class="dataFontStyle" v-else-if="dataItem.direction == 'inbound'">
{{dataItem.cid_num}}
<span v-if="dataItem.callstate == 'EARLY'" >回铃</span>
<span v-if="dataItem.callstate == 'RINGING'" >振铃</span>
<span v-if="dataItem.callstate == 'ACTIVE'" >通话</span>
{{dataItem.dest}}
</el-col>
<br>
</el-row>
</div>
</div>
</li>
监听全局对象 globalData.extTelTalkData 的变化,实时显示到界面上
<script>
// 在子组件中注入全局对象
import { inject, watch } from 'vue'
export default {
// 组件名称
name: 'RightSideComponent',
setup() {
// 注入全局对象
const globalData = inject('globalData');
//监听全局对象的变化
watch(() => globalData.extTelTalkData, (newValue) => {
// 更新自己的状态
globalData.extTelTalkData=newValue;
console.log("RightSideComponent watch "+globalData.extTelTalkData.length);
})
return {
globalData
};
}
}
</script>