类别组件 api 调用已创建
Category component do api call on created
目前我的类别组件正在创建 http api 调用。
所以当我从索引转到类别时,http 调用的结果是有效的。
但是现在,当我更改类别时,我从 localhost:8080/category/1
转到 localhost:8080/category/2
我的组件没有重新呈现,所以它没有再次创建,我的 http 调用函数也没有再次触发如何我愿意。
async created() {
try {
console.log(this.id);
const response = await axios.get(`/api/category/getOne.php?id=${this.id}`, axiosConfig);
console.log(response.data.records[0].name);
this.category = [response.data.records[0].name];
} catch (e) {
this.errors.push(e);
console.log(this.errors);
}
}
你们对我有什么建议,我是否应该将此 http 调用不放在 created ()
中,而是放在 methods {}
中,然后检测 url id 是否更改并执行此函数什么时候改变?或者有更好的 vue 方法吗?
我将上面的代码移动到 methods {}
并在 created()
和 id 更改时调用它,如下所示:
created() {
this.getData(this.id);
},
watch: {
'$route.params.id'(newId, oldId) {
this.getData(newId);
}
}
正如@Belmin Bedak 在评论部分所建议的那样。
目前我的类别组件正在创建 http api 调用。
所以当我从索引转到类别时,http 调用的结果是有效的。
但是现在,当我更改类别时,我从 localhost:8080/category/1
转到 localhost:8080/category/2
我的组件没有重新呈现,所以它没有再次创建,我的 http 调用函数也没有再次触发如何我愿意。
async created() {
try {
console.log(this.id);
const response = await axios.get(`/api/category/getOne.php?id=${this.id}`, axiosConfig);
console.log(response.data.records[0].name);
this.category = [response.data.records[0].name];
} catch (e) {
this.errors.push(e);
console.log(this.errors);
}
}
你们对我有什么建议,我是否应该将此 http 调用不放在 created ()
中,而是放在 methods {}
中,然后检测 url id 是否更改并执行此函数什么时候改变?或者有更好的 vue 方法吗?
我将上面的代码移动到 methods {}
并在 created()
和 id 更改时调用它,如下所示:
created() {
this.getData(this.id);
},
watch: {
'$route.params.id'(newId, oldId) {
this.getData(newId);
}
}
正如@Belmin Bedak 在评论部分所建议的那样。