Rma*_*x77 6 javascript svelte svelte-3
我正在开发一个组件,我需要使用它的上下文。但我不知道为什么当我使用 getContext 时,它是未定义的。
这是我在第一个组件(索引组件)上的代码的一部分:
import { setContext } from 'svelte';
import {onMount} from "svelte";
let tempSuggest;
const suggestModel = {
category_id: 1,
title: "",
images: [{}],
catalogues: [{}],
dependent_attributes: [{}],
independent_attributes: [{}],
};
$: tempSuggest = Object.assign({}, suggestModel);
onMount(() => {
setContext(clientProductSuggest, tempSuggest);
});
Run Code Online (Sandbox Code Playgroud)
在第一个组件的html代码中(在索引文件末尾加载子组件):
<svelte:component this={component} {...props}/>
Run Code Online (Sandbox Code Playgroud)
在第二个组件中:
import { getContext } from 'svelte';
const c = getContext('clientProductSuggest');
console.log(c);
Run Code Online (Sandbox Code Playgroud)
现在上下文未定义。
Rom*_*ere 10
它可能不会涵盖这个问题,但请记住,这只getContext适用于该组件的子级setContext。
对于跨组件共享,我们应该使用商店。
我写这个答案是因为如果我在这里找到它,它会节省我几个小时的研究和发布到精简社区聊天的时间。
| 归档时间: |
|
| 查看次数: |
3093 次 |
| 最近记录: |