close事件 vue_如何在Vue开关更改时触发事件

I have a Vue component that has a vue-switch element. When the component is loaded, the switch has to be set to ON or OFF depending on the data. This is currently happening within the 'mounted()' method. Then, when the switch is toggled, it needs to make an API call that will tell the database the new state. This is currently happening in the 'watch' method.

The problem is that because I am 'watching' the switch, the API call runs when the data gets set on mount. So if it's set to ON and you navigate to the component, the mounted() method sets the switch to ON but it ALSO calls the toggle API method which turns it off. Therefore the view says it's on but the data says it's off.

I have tried to change the API event so that it happens on a click method, but this doesn't work as it doesn't recognize a click and the function never runs.

How do I make it so that the API call is only made when the switch is clicked?

HTML

VUE

data: function() {

return {

toggle: false,

noAvailalableMonitoring: false

}

},

computed: {

report() { return this.$store.getters.currentReport },

isBeingMonitored() { return this.$store.getters.isBeingMonitored },

availableMonitoring() { return this.$store.getters.checkAvailableMonitoring }

},

mounted() {

this.toggle = this.isBeingMonitored;

},

watch: {

toggle: function() {

if(this.availableMonitoring) {

let dto = {

reportToken: this.report.reportToken,

version: this.report.version

}

this.$store.dispatch('TOGGLE_MONITORING', dto).then(response => {

}, error => {

console.log("Failed.")

})

} else {

this.toggle = false;

this.noAvailalableMonitoring = true;

}

}

}

解决方案

I would recommend using a 2-way computed property for your model (Vue 2).

Attempted to update code here, but obvs not tested without your Vuex setup.

For reference, please see Two-Way Computed Property

data: function(){

return {

noAvailableMonitoring: false

}

},

computed: {

report() { return this.$store.getters.currentReport },

isBeingMonitored() { return this.$store.getters.isBeingMonitored },

availableMonitoring() { return this.$store.getters.checkAvailableMonitoring },

toggle: {

get() {

return this.$store.getters.getToggle;

},

set() {

if(this.availableMonitoring) {

let dto = {

reportToken: this.report.reportToken,

version: this.report.version

}

this.$store.dispatch('TOGGLE_MONITORING', dto).then(response => {

}, error => {

console.log("Failed.")

});

} else {

this.$store.commit('setToggle', false);

this.noAvailableMonitoring = true;

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值