切换语言包,定义在 data 里,无法做到 响应式。 解决方法
- template
<button class="yzbtn" @click="getCodeVal" :disabled="disabled">{{codeName }}</button>
- js
data() {
return {
// codeName: '获取验证码', 无法响应式
name:'', // 过渡 赋值给验证码codeName
disabled: false,
clickyzm:false, // true 正在倒计时 false 倒计时结束
};
},
// 监控自己定义的变量,该变量不在data里面声明,直接在computed里面定义.
computed: {
// codeName() {
// return this.$t('login.huoqu')
// },
codeName:{
// 设置
set(val){
console.log('验证码新的值',val);
this.name = val;
},
// 获取
get(){
let res;
if(this.clickyzm){
res = this.name;
} else {
res = this.$t('login.huoqu')
}
return res;
}
}
},
methods: {
getCodeVal() {
let num = 60;
this.disabled = true;
this.timer = setInterval(() => {
if (num > 1) {
this.clickyzm = true;
num--;
this.codeName = num + 's';
} else {
this.clickyzm = false;
this.disabled = false;
clearInterval(this.timer)
}
}, 1000)
}
}
该文章探讨了在Vue.js应用中如何处理语言包切换的问题,特别是当定义在data中的codeName无法响应式改变时。通过在computed属性中创建getter和setter方法,结合methods中的事件处理函数实现了验证码按钮的动态更新,包括倒计时功能。在点击按钮后,codeName会根据clickyzm的状态显示倒计时或默认语言包值。
3万+

被折叠的 条评论
为什么被折叠?



