gpt4 book ai didi

javascript - 使用 axios 时 Vue Watch 不会被触发

转载 作者:搜寻专家 更新时间:2023-10-30 22:37:37 25 4
gpt4 key购买 nike

大家好,我有这段代码可以使用 axios 从数据库中获取数据,并且在 .then() 函数中我设置了一个数据属性,watch 不会触发。这是我目前拥有的一些代码。提前谢谢你!

export default {

name: '..',
data() {
return {
autocompleteOn: false
}
},

watch: {
autocompleteOn(oldVal, newVal) {
console.log('autocomplet') // doesnt trigger this
}
},

methods: {
fetchAutocompleteResults: _.debounce((filter) => {
let $this = this;



let data = {
filter: filter,
page: $this.page
};

filter.resources.response = [];
filter.loading = true;

axios.post(BASE_URL + '/search/filter', data).then(function(response) {
if (response.data.length) {
filter.autocompleteOn = true;
$this.autocompleteOn = true;
filter.resources.response = filter.resources.response.concat(response.data);
$this.currentFilter = filter;
$this.page++;
console.log($this.autocompleteOn); // this is correct
}

filter.loading = false;
});
}, 300)
}

}

最佳答案

带有箭头函数的 debounce 使 this 成为 Vue 实例以外的东西(例如 window)。

代替:

methods: {
fetchAutocompleteResults: _.debounce((filter) => {

使用:

methods: {
fetchAutocompleteResults: _.debounce(function (filter) {
// ^^^^^^^^ ^^^

演示:

new Vue({
el: '#app',
data() {
return {
autocompleteOn: false
}
},
watch: {
autocompleteOn(oldVal, newVal) {
console.log('autocomplet') // doesnt trigger this
}
},
methods: {
fetchAutocompleteResults: _.debounce(function (filter) { // CHANGED from arrow function
let $this = this;

let data = {
filter: filter,
page: $this.page
};

filter.resources.response = [];
filter.loading = true;

// changed data for demo
data = [{title: 'foo', body: 'bar', userId: 1}];

// changed URL for demo
axios.post('https://jsonplaceholder.typicode.com/posts', data).then(function(response) {
if (response.data.length) {
filter.autocompleteOn = true;
$this.autocompleteOn = true;
filter.resources.response = filter.resources.response.concat(response.data);
$this.currentFilter = filter;
$this.page++;
console.log($this.autocompleteOn); // this is correct
}

filter.loading = false;
});
}, 300)
}
})
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.5/lodash.min.js"></script>

<div id="app">
<button @click="fetchAutocompleteResults({resources: {}})">fetchAutocompleteResults</button>
</div>

关于javascript - 使用 axios 时 Vue Watch 不会被触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49945943/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com