// vue2 组件封装如下:
语音播报
var request_init; // 接收setTimeout() 返回的 ID 值
var order_id = 0; // 初始化订单id
$.ajaxSettings.async = false; // 禁止异步请求,
// 取最新的订单id
$.get('/order/voice', function ($data) {
order_id = $data.order_id;
})
export default {
props: { //模板传递属性
voiceStatus: {
type: String,
required: true
},
},
data(){
return {
openVoice:this.voiceStatus,
validate:false
}
},
// 加载完成后执行
mounted:function(){
if(this.openVoice==1){
this.voice_play();
}
},
methods: {
// 封装播放语音的方法
voice_play(){
var audio=document.getElementById('audio'); // 音频播放对象标签
var $this=this;
$.ajax({
url: '/order/voice',
type: 'get',
data: {order_id: order_id},
dataType: "json",
success: function($data){
if ($data != '' && $data != undefined) { // 如果有语音的情况处理
$this.validate=false; // 来网络时开启按钮
order_id = $data.order_id;
audio.src = $data.voice;
audio.play();
audio.onended = function () {
if($this.openVoice==1) {
clearTimeout(request_init);
request_init=setTimeout(function(){$this.voice_play()},2000); // 以匿名函数形式设置settimeout即可实现两秒请求一次
}
}
} else {
$this.validate=false; // 来网络时开启按钮
clearTimeout(request_init);
request_init=setTimeout(function(){$this.voice_play()},2000);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$this.validate=true; // 断网就禁用此按钮 继续往下执行请求
request_init=setTimeout(function(){$this.voice_play()},2000);
//console.log(XMLHttpRequest);
}
})
},
change_voice(event){
var audio=document.getElementById('audio'); // 音频播放对象标签
var $this=this;
if (event==1) { // 判断是否选中(表示开启语音)
$this.openVoice='0'; // 在回调未成功之前不能改变按钮的状态
// 再次取最新的订单号
$.get('/order/voice', function ($data) {order_id = $data.order_id;})
$this.$http.get('/system/voice/index', {params: {status: 1}})
.then(res => {
if(res.data==1){ // res.data由后台返回 1表示成功 0表示失败,目前只考虑成功
$this.openVoice='1'; // 在回调成功之后改变按钮的状态
$this.voice_play();
}
})
.catch(_=>{})
} else { // 关闭
$this.openVoice='1'; // 在回调未成功之前不能改变按钮的状态
audio.pause(); // 停止播放
$this.$http.get('/system/voice/index', {params: {status: 2}})
.then(res => {
if(res.data==1){
$this.openVoice='0'; // 在回调成功之后改变按钮的状态
clearTimeout(request_init); // 终止setTimeout 定时回调
}
})
.catch(_=>{
$this.validate=true; // 断网就禁用此按钮
request_init=setTimeout(function(){$this.voice_play()},2000);
})
}
}
},
};
// ----------------------------------------------以上为vue2的组件-----------------------------------------------仅供参考
// 在html模版中使用如下: