简体   繁体   English

如何在苗条的商店中引用反应式 $ 变量?

[英]how to reference a reactive $ variable inside a svelte store?

I'll brief.我简要介绍一下。

I have a reactive variable that updates everytime a user adds a product to a shoppingcart.我有一个反应变量,每次用户将产品添加到购物车时都会更新。

let cartItems = []
$: cartLength = cartitems.length;

Now I want to put the length of the cart items into icon in a different component.现在我想将购物车项目的长度放入不同组件中的图标中。 So I tried to create and share it with the rest of the component.所以我尝试创建并与组件的rest共享。

import { writable } from 'svelte/store';
export const cartItemsLength = writable("");

In my cartitems component.在我的 caritems 组件中。 I tried to update the store after importing it into my component:将商店导入我的组件后,我尝试更新商店:

cartItemsLength.update(value=>{
value =  cartLength
})

But it shows undefined in my dev tools everytime.但它每次都在我的开发工具中显示未定义。 I tried $cartLength {$cartLength} So, my question, how do you assign that cartLength variable to the value inside the store update function?我尝试了 $cartLength {$cartLength} 所以,我的问题是,如何将该 cartLength 变量分配给商店更新 function 内的值?

writable store's update function should have a return value to be set in the store.可写存储的更新 function 应该有一个返回值要在存储中设置。

https://svelte.dev/docs#writable https://svelte.dev/docs#writable

// File cartitems.svelte

import { writable } from 'svelte/store';

export const cartItemsLength = writable(0);

let cartItems = [];
$: cartLength = cartItems.length;

// 1. use store's update function
cartItemsLength.update(value=> {
  return cartLength;
});

// 2. or you can just use $store if in .svelte script
$cartItemsLength = cartLength;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM