[英]Exported data is null when using it in another javascript vue js file
i am developing a shopify theme, currently i am working on shopping cart page, i have CartForm.js file where i am importing data from cartData.js file.我正在开发一个 shopify 主题,目前我正在处理购物车页面,我有 CartForm.js 文件,我正在从 cartData.js 文件中导入数据。 This is CartForm.js...这是 CartForm.js...
import { store } from "./../shared/cartData.js";
if (document.querySelector('.cart-form')) {
let productForm = new Vue({
el:".cart-form",
delimiters: ['${', '}'],
data(){
return{
cart:null,
}
},
created(){
this.getCart();
},
methods:{
getCart(){
store.getCart();
this.cart=store.state.cartData;
console.log("cart data: "+this.cart);
},
and this is cartData.js file这是 cartData.js 文件
export const store = {
state: {
cartData:null
},
getCart(){
alert("store get cart called!...")
axios.get('/cart.js')
.then( response => {
this.state.cartData=response.data;
console.log("Responsed data="+this.state.cartData);
})
.catch( error => {
new Noty({
type: 'error',
layout: 'topRight',
text: 'There was an error !!'
}).show();
});
}
}
As you can see i am explicitly calling store.getCart();如您所见,我明确调用 store.getCart(); in CartForm's getCart() method, and when "Responsed data" gets printed it shows that this.state.cartData filled with data, but when i am using it like this: this.cart=store.state.cartData;在 CartForm 的 getCart() 方法中,当打印“响应数据”时,它显示 this.state.cartData 填充了数据,但是当我像这样使用它时: this.cart=store.state.cartData; this.cart is null, why is null? this.cart 是 null,为什么是 null? Any help is appreciated任何帮助表示赞赏
This happens because your API takes a while to respond, but JavaScript continues running the function in parallel.发生这种情况是因为您的 API 需要一段时间才能响应,但 JavaScript 继续并行运行 function。 Your state is still 'null' while the call hasn't returned, thus this.cart will be set to null, unless you tell JavaScript to wait until the call is finished.您的 state 在呼叫尚未返回时仍为“null”,因此 this.cart 将设置为 null,除非您告诉 JavaScript 等待呼叫完成。
Try making the getCart()
method an asynchronous function:尝试将getCart()
方法设为异步 function:
methods:{
async getCart(){
await store.getCart();
this.cart=store.state.cartData;
console.log("cart data: "+this.cart);
},
If cart should always be the same as the data in your store, a better way to do this might be to use a computed
property for cart.如果购物车应该始终与商店中的数据相同,那么更好的方法可能是使用购物车的computed
属性。 This returns the store.state directly and will help you keep a single source of truth for your data.这将直接返回 store.state 并将帮助您为数据保留单一的真实来源。
computed: {
cart() {
return store.state.cartData
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.