string-function 相关问题


为什么将operator()作为std::function调用不起作用

考虑这个旨在收集字符串序列的小类: 班级问题_t期末 { 私人的: std::vector m_issues; 民众: constexpr void 运算符()(std::string&a...


Laravel 中的策略对我不起作用,这是我的代码

我无法让策略在我的 Laravel 项目中工作,我安装了一个新项目来从头开始测试,我有这个控制器: 我无法让策略在我的 Laravel 项目中工作,我安装了一个新项目来从头开始测试,我有这个控制器: <?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Models\User; class UserController extends Controller { public function index() { $this->authorize('viewAny', auth()->user()); return response("Hello world"); } } 本政策: <?php namespace App\Policies; use Illuminate\Auth\Access\Response; use App\Models\User; class UserPolicy { public function viewAny(User $user): bool { return true; } } 这是我的模型 <?php namespace App\Models; // use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { use HasApiTokens, HasFactory, Notifiable; /** * The attributes that are mass assignable. * * @var array<int, string> */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for serialization. * * @var array<int, string> */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast. * * @var array<string, string> */ protected $casts = [ 'email_verified_at' => 'datetime', 'password' => 'hashed', ]; } 我收到错误 403:此操作未经授权。我希望有人能帮助我解决我的问题。谢谢你 我也尝试过修改AuthServiceProvider文件,但没有任何改变。 必须在 App\Providers\AuthServiceProvider 中添加您的策略吗? protected $policies = [ User::class => UserPolicy::class ]; 您需要指定您正在使用的模型。具体来说,就是User。因此,传递当前登录的用户: $this->authorize('viewAny', auth()->user()); 此外,您正在尝试验证用户是否有权访问该页面。确保尝试访问该页面的人是用户,以便策略可以授权或不授权。 要在没有入门套件的情况下进行测试,请创建一个用户并使用它登录。 <?php namespace App\Http\Controllers; use Illuminate\Support\Facades\Auth; class UserController extends Controller { public function index() { $user = \App\Models\User::factory()->create(); Auth::login($user); $this->authorize('viewAny', auth()->user()); return response("Hello world"); } } 但是,如果您希望授予访客用户访问权限,您可以使用 ? 符号将 User 模型设为可选: public function viewAny(?User $user) { return true; }


jQuery Ajax 在 php 同一页面上传递值 - 更新

如何找回: 如何找回: <div id="test"> <?php if (isset($_POST['sweets'])) { ob_clean(); echo $_POST['sweets']; exit; } ?> </div> <form id="a" action="" method="post"> <select name="sweets" onchange="change()" id="select1"> <option >Chocolate</option> <option selected="selected">Candy</option> <option >Taffy</option> <option >Caramel</option> <option >Fudge</option> <option >Cookie</option> </select> </form> <!-- Script --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> function change() { var sweets = $("#select1").val(); $.ajax({ type: "POST", data: { sweets: sweets }, success: function(data) { $("#test").html(data); } }); } </script> 将值传递给 php 字符串: $string = $_POST['sweets']; <!-- I'm looking for this: --> 我希望这是可能的。我在 stackoverflow 和 google 上寻找答案,但找不到适合我的目的的答案。 对于同一个页面的ajax/PHP脚本,可以将PHP放在脚本的最前面,当有POST提交数据时以exit结束 为了使其更有意义,您应该返回与您通过 POST 提交的内容相关的内容(这是甜食的类型),作为示例,我们展示其一般定义。我们可以使用 switch,这是用于此目的的常用结构: switch ($string) { case "Chocolate": echo "Chocolate is made from cocoa beans, the dried and fermented seeds of the cacao tree"; break; case "Candy": echo "Candy is a sweet food made from sugar or chocolate, or a piece of this"; break; case "Taffy": echo "Taffy is a type of candy invented in the United States, made by stretching and/or pulling a sticky mass of a soft candy base"; break; case "Caramel": echo "Caramel is made of sugar or syrup heated until it turns brown, used as a flavouring or colouring for food or drink"; break; case "Fudge": echo "Fudge is a dense, rich confection typically made with sugar, milk or cream, butter and chocolate or other flavorings"; break; case "Cookie": echo "A cookie (American English) or biscuit (British English) is a baked snack or dessert that is typically small, flat, and sweet"; break; } exit; } ?> 所以以下是示例代码: <?php if (isset($_POST['sweets'])) { // ob_clean(); $string = $_POST['sweets']; switch ($string) { case "Chocolate": echo "Chocolate is made from cocoa beans, the dried and fermented seeds of the cacao tree"; break; case "Candy": echo "Candy is a sweet food made from sugar or chocolate, or a piece of this"; break; case "Taffy": echo "Taffy is a type of candy invented in the United States, made by stretching and/or pulling a sticky mass of a soft candy base"; break; case "Caramel": echo "Caramel is made of sugar or syrup heated until it turns brown, used as a flavouring or colouring for food or drink"; break; case "Fudge": echo "Fudge is a dense, rich confection typically made with sugar, milk or cream, butter and chocolate or other flavorings"; break; case "Cookie": echo "A cookie (American English) or biscuit (British English) is a baked snack or dessert that is typically small, flat, and sweet"; break; } exit; } ?> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <select name="sweets" onchange="change()" id="select1"> <option value="">Please select</option> <option >Chocolate</option> <option >Candy</option> <option >Taffy</option> <option >Caramel</option> <option >Fudge</option> <option >Cookie</option> </select> <br><br> <div id="test"></div> <script> function change() { var sweets = $("#select1").val(); $.ajax({ type: "POST", data: { sweets: sweets }, success: function(data) { $("#test").html(data); } }); } </script>


如何在 JavaScript 中转义 XML 实体?

在 JavaScript(服务器端 NodeJS)中,我正在编写一个生成 XML 作为输出的程序。 我通过连接字符串来构建 XML: str += '<' + key + '>'; str += 值; str += ' 在 JavaScript(服务器端 NodeJS)中,我正在编写一个生成 XML 作为输出的程序。 我通过连接字符串来构建 XML: str += '<' + key + '>'; str += value; str += '</' + key + '>'; 问题是:如果value包含'&'、'>'或'<'等字符怎么办? 逃离这些角色的最佳方法是什么? 或者是否有任何 JavaScript 库可以转义 XML 实体? 对于相同的结果,这可能会更有效一些: function escapeXml(unsafe) { return unsafe.replace(/[<>&'"]/g, function (c) { switch (c) { case '<': return '&lt;'; case '>': return '&gt;'; case '&': return '&amp;'; case '\'': return '&apos;'; case '"': return '&quot;'; } }); } HTML 编码只是将 &、"、'、< 和 > 字符替换为其实体等效项。顺序很重要,如果您不首先替换 & 字符,您将对某些实体进行双重编码: if (!String.prototype.encodeHTML) { String.prototype.encodeHTML = function () { return this.replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&apos;'); }; } 如@Johan B.W. de Vries 指出,这会对标签名称产生问题,我想澄清一下,我假设这是用于 value only 相反,如果您想解码 HTML 实体1,请确保在完成其他操作之后将 &amp; 解码为 &,这样就不会双重解码任何实体: if (!String.prototype.decodeHTML) { String.prototype.decodeHTML = function () { return this.replace(/&apos;/g, "'") .replace(/&quot;/g, '"') .replace(/&gt;/g, '>') .replace(/&lt;/g, '<') .replace(/&amp;/g, '&'); }; } 1只是基础知识,不包括&copy;到©或其他类似的东西 就图书馆而言。 Underscore.js(或 Lodash,如果您愿意)提供了一个 _.escape 方法来执行此功能。 如果您有 jQuery,这里有一个简单的解决方案: String.prototype.htmlEscape = function() { return $('<div/>').text(this.toString()).html(); }; 像这样使用它: "<foo&bar>".htmlEscape(); -> "&lt;foo&amp;bar&gt" 您可以使用以下方法。我已将其添加到原型中以便于访问。 我还使用了负前瞻,因此如果您调用该方法两次或更多次,它不会弄乱事情。 用途: var original = "Hi&there"; var escaped = original.EncodeXMLEscapeChars(); //Hi&amp;there 解码由 XML 解析器自动处理。 方法: //String Extenstion to format string for xml content. //Replces xml escape chracters to their equivalent html notation. String.prototype.EncodeXMLEscapeChars = function () { var OutPut = this; if ($.trim(OutPut) != "") { OutPut = OutPut.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;"); OutPut = OutPut.replace(/&(?!(amp;)|(lt;)|(gt;)|(quot;)|(#39;)|(apos;))/g, "&amp;"); OutPut = OutPut.replace(/([^\\])((\\\\)*)\\(?![\\/{])/g, "$1\\\\$2"); //replaces odd backslash(\\) with even. } else { OutPut = ""; } return OutPut; }; 注意,如果 XML 中有 XML,那么所有的正则表达式都不好。 相反,循环字符串一次,并替换所有转义字符。 这样,您就不能两次碰到同一个角色。 function _xmlAttributeEscape(inputString) { var output = []; for (var i = 0; i < inputString.length; ++i) { switch (inputString[i]) { case '&': output.push("&amp;"); break; case '"': output.push("&quot;"); break; case "<": output.push("&lt;"); break; case ">": output.push("&gt;"); break; default: output.push(inputString[i]); } } return output.join(""); } 我最初在生产代码中使用了已接受的答案,发现大量使用时它实际上非常慢。这是一个更快的解决方案(以两倍以上的速度运行): var escapeXml = (function() { var doc = document.implementation.createDocument("", "", null) var el = doc.createElement("temp"); el.textContent = "temp"; el = el.firstChild; var ser = new XMLSerializer(); return function(text) { el.nodeValue = text; return ser.serializeToString(el); }; })(); console.log(escapeXml("<>&")); //&lt;&gt;&amp; 也许你可以试试这个, function encodeXML(s) { const dom = document.createElement('div') dom.textContent = s return dom.innerHTML } 参考 添加 ZZZZBov 的答案,我发现这更干净,更容易阅读: const encodeXML = (str) => str .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&apos;'); 此外,所有五个字符都可以在这里找到,例如:https://www.sitemaps.org/protocol.html 请注意,这仅对值进行编码(如其他人所述)。 现在我们有了字符串插值和其他一些现代化改进,现在是时候进行更新了。并使用对象查找,因为它确实应该这样做。 const escapeXml = (unsafe) => unsafe.replace(/[<>&'"]/g, (c) => `&${({ '<': 'lt', '>': 'gt', '&': 'amp', '\'': 'apos', '"': 'quot' })[c]};`); 从技术上讲,&、 不是有效的 XML 实体名称字符。如果您不能信任关键变量,则应该将其过滤掉。 < and >如果您希望它们作为 HTML 实体转义,您可以使用类似 http://www.strictly-software.com/htmlencode . 如果之前有东西被逃脱,你可以尝试这个,因为这不会像许多其他人那样双重逃脱 function escape(text) { return String(text).replace(/(['"<>&'])(\w+;)?/g, (match, char, escaped) => { if(escaped) { return match; } switch(char) { case '\'': return '&apos;'; case '"': return '&quot;'; case '<': return '&lt;'; case '>': return '&gt;'; case '&': return '&amp;'; } }); } 这很简单: sText = ("" + sText).split("<").join("&lt;").split(">").join("&gt;").split('"').join("&#34;").split("'").join("&#39;");


java中的Boolean.valueOf(String)和BooleanUtils.toBoolean(String)?

我有一个 Boolean.valueOf(String) 和 BooleanUtils.toBoolean(String) 之间不同的问题 。 我使用我的应用程序就像代码 BooleanUtils.toBoolean(defaultInfoRow.getFolderType()) 一样


释放函数体内std::function的内存

我需要将 std::function 作为 void 指针传递以异步执行,因此我在堆上创建了一个 std::function 。删除函数体内的 std::function 对象是否安全?请看...


具有 TimestampableEntity 特征的实体在 PUT 操作中失败

我正在全新安装 API Platform (v3.2.7),并且使用 Gedmo\Timestampable\Traits\TimestampableEntity 这是我的实体(问候语示例) 我正在全新安装 API Platform (v3.2.7),并且正在使用 Gedmo\Timestampable\Traits\TimestampableEntity 这是我的实体(问候语示例) <?php namespace App\Entity; use ApiPlatform\Metadata\ApiResource; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; use Gedmo\Timestampable\Traits\TimestampableEntity; #[ApiResource] #[ORM\Entity] class Greeting { use TimestampableEntity; #[ORM\Id] #[ORM\Column(type: "integer")] #[ORM\GeneratedValue] private ?int $id = null; #[ORM\Column] #[Assert\NotBlank] public string $name = ""; public function getId(): ?int { return $this->id; } } 和我的 config/services.yaml gedmo.listener.timestampable: class: Gedmo\Timestampable\TimestampableListener tags: - { name: doctrine.event_listener, event: 'prePersist' } - { name: doctrine.event_listener, event: 'onFlush' } - { name: doctrine.event_listener, event: 'loadClassMetadata' } 它在 POST 操作上工作正常,但在执行 PUT 时失败。我收到此错误 执行查询时发生异常:SQLSTATE[23000]: 完整性约束违规:1048 列“created_at”不能 空 我使用的版本是:symfony 6.4.1,doctrine 2.12,gedmo 3.14 我最终做的是使用 PATCH 而不是 PUT。所以我可以编辑部分实体,并且特征仍然更新 updated_at 字段


从数据库中提取后出现在<textarea>中

数据首先从 捕获。 1号线 2号线 3号线 ETC 它在存储到数据库之前通过此函数发送(我愿意接受更好的解决方案,但如果 PDO 是其中之一......</desc> <question vote="0"> <p>数据首先从 <pre><code><textarea></code></pre> 捕获。</p> <pre><code>Line1 Line2 Line3 etc </code></pre> <p>它在存储到数据库之前通过此函数发送(我愿意接受更好的解决方案,但如果 PDO 是其中之一,我不理解它并且尚未使其工作)</p> <pre><code>function test_input($data) { global $conn; $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); $data = mysqli_real_escape_string($conn, $data); return $data; } </code></pre> <p>这是我防止注射的方法(不是我的方法,而是我发现迄今为止效果很好的一种方法,它给我带来了<pre><code><textarea></code></pre>中换行的问题)。</p> <p>我尝试从数据库中提取数据并将其显示在<pre><code><textarea></code></pre>中,它显示<pre><code>\r\n</code></pre>而不是换行。它存储在带有换行符的数据库中(我没有看到<pre><code>\r\n</code></pre>,但我看到了新行上的数据)。</p> <p>我已经尝试过<pre><code>nl2br()</code></pre>,我已经尝试过<pre><code>html_entity_decode()</code></pre>,我已经尝试过<pre><code>str_replace()</code></pre>从<pre><code>\r\n</code></pre>到<pre><code><br></code></pre>(然后它只显示<pre><code><br></code></pre>文字而不是<pre><code>\r\n</code></pre>)。</p> <p>根据我在这个网站上发现的研究,这是我在将其存储到数据库之前对其所做的事情造成的,但没有一个解决方案对我有用。</p> </question> <answer tick="true" vote="2"> <p>将文本中的 <pre><code>\r\n</code></pre> 替换为 <pre><code>&#13;&#10;</code></pre>,然后将其放入文本区域并向用户显示。</p> <p>它对我有用。</p> </answer> <answer tick="false" vote="0"> <p>试试这个可能会有帮助</p> <pre><code><?php function nl2br2($string) { $string = str_replace(array("\r\n", "\r", "\n"), "<br />", $string); return $string; } ?> </code></pre> </answer> <answer tick="false" vote="0"> <p>Html 与 php 和 windows(回车符和换行符)。勒 思考会发生什么 当缓冲区中有一个值字段时。缓冲区可以来自或去往输入/输出设备 缓冲区内的内容可能需要替换为适合设备的字符串。 从数据库逐行或从 SQL api 查询提取数据将需要重复正则表达式和替换操作,直到所有 表达方式发生改变。在输入进入数据库字段之前对其进行防弹检查始终是一个好主意。 我遇到了由额外数据(转义序列)引起的打印问题,该问题导致打印机无法正常工作 停止并等待重置序列。没有人理解为什么打印作业无法打印类似的内容 12个月。我编写了一个过滤器并将其添加到打印机界面。问题解决了</p> </answer> </body></html>


如何以模板文字类型返回?

我使用这样的模板文字类型: 输入 HelloSomething = `你好 ${string}` 常量字符串='世界' 函数 sayHello(string: string): HelloSomething { 返回“你好”+字符串 } (游乐场...


azure function 应用程序环境的配置值

您正在开发一个Azure Function App。您使用 Azure Function App 主机不支持的语言开发代码。代码语言支持 HTTP 原语。 您必须部署...


javascript:如何中止 $.post()

我的post方法如下图: $(".buttons").click(function(){ var gettopic=$.post("topic.php", {id: topicId}, function(result){ // 处理返回结果的代码 }); }) 我尝试...


encodeURIComponent 的结果在服务器端未正确解码

我正在努力正确编码/解码 JSON 字符串,以便通过 GET 请求中的查询字符串发送。 ...</desc> <question vote="0"> <p>我正在努力正确编码/解码 JSON 字符串,以便通过 GET 请求中的查询字符串发送。</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script type=&#34;text/javascript&#34;&gt; function executeRequest(applyUriEncode) { var json = &#39;{&#34;foo&#34;:&#34;💀🍕⚡💎&amp;🎁❤很久很久以前&#34;}&#39;; var xmlhttp = new XMLHttpRequest(); xmlhttp.open(&#39;GET&#39;, &#39;https://example.com/test.php?json=&#39;+(applyUriEncode ? encodeURIComponent(json) : json), false); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 &amp;&amp; xmlhttp.status == 200) { console.log(&#34;applyUriEncode: &#34;+(applyUriEncode ? &#34;true\n&#34; : &#34;false\n&#34;)); console.log(xmlhttp.responseText+&#34;\n&#34;); } }; xmlhttp.send(); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;button onClick=&#34;executeRequest(true);&#34;&gt;Submit encoded&lt;/button&gt; &lt;button onClick=&#34;executeRequest(false);&#34;&gt;Submit unencoded&lt;/button&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <pre><code>&lt;?php // test.php echo $_GET[&#39;json&#39;]; </code></pre> <p>点击<pre><code>Submit encoded</code></pre>和<pre><code>Submit unencoded</code></pre>时的输出:</p> <pre><code>applyUriEncode: true {&#34;foo&#34;:&#34;💀ðŸ•âš¡ðŸ’Ž&amp;ðŸŽâ¤å¾ˆä¹…很久以å‰&#34;} applyUriEncode: false {&#34;foo&#34;:&#34;💀🍕⚡💎 </code></pre> <p>期望的输出是</p> <pre><code>{&#34;foo&#34;:&#34;💀🍕⚡💎&amp;🎁❤很久很久以前&#34;} </code></pre> <p>我需要对 JSON 进行编码,否则,特殊字符(例如 <pre><code>&amp;</code></pre>)会破坏字符串。然而,PHP 似乎没有正确解码 <pre><code>encodeURIComponent</code></pre> 的结果。我在服务器端尝试了 <pre><code>urldecode</code></pre>,但这并没有改变任何事情(输出保持不变)。</p> <p>我觉得这是一个基本问题,在 StackOverflow 上应该有答案,但我找不到。我发现了大量具有类似问题的问题,但没有一个问题能让我找到针对这个特定问题的解决方案。</p> </question> <answer tick="false" vote="0"> <p>您遇到的问题与字符编码有关。当您在 JavaScript 中使用 <pre><code>encodeURIComponent</code></pre> 时,它会正确对 JSON 字符串(包括 Unicode 字符)进行百分比编码。但是,当 PHP 接收查询字符串时,它不会自动将百分比编码的 Unicode 字符解码回其原始形式。</p> <p>要解决此问题,您需要确保 PHP 将传入数据解释为 UTF-8,然后使用 <pre><code>urldecode</code></pre> 解码百分比编码的字符串。以下是如何修改 PHP 代码以获得所需的输出:</p> <pre><code>&lt;?php // test.php // Get the raw, percent-encoded JSON string from the query parameter $encodedJson = $_GET[&#39;json&#39;]; // Manually decode the percent-encoded string $decodedJson = urldecode($encodedJson); // Ensure that the string is treated as UTF-8 $decodedJson = mb_convert_encoding($decodedJson, &#39;UTF-8&#39;, &#39;UTF-8&#39;); // Output the decoded JSON string echo $decodedJson; </code></pre> <p>此代码片段假设您的 PHP 环境配置为使用 UTF-8 作为默认字符编码。如果不是,您可能需要在脚本开头使用 <pre><code>mb_internal_encoding(&#39;UTF-8&#39;)</code></pre> 将字符编码显式设置为 UTF-8。</p> <p>此外,需要注意的是,当您在查询字符串中发送 JSON 数据时,应始终使用 <pre><code>encodeURIComponent</code></pre> 对 JSON 字符串进行编码。这是因为查询字符串具有某些保留字符(如 <pre><code>&amp;</code></pre>、<pre><code>=</code></pre>、<pre><code>+</code></pre>、<pre><code>?</code></pre> 等),如果不进行编码,可能会破坏 URL 的结构。 <pre><code>encodeURIComponent</code></pre> 函数确保这些字符被安全编码,这样它们就不会干扰 URL 的格式。</p> <p>在客户端,当将 <pre><code>encodeURIComponent</code></pre> 标志设置为 <pre><code>applyUriEncode</code></pre> 时,您的 JavaScript 代码使用 <pre><code>true</code></pre> 是正确的。始终使用编码版本在查询字符串中发送数据,以避免特殊字符出现问题。</p> </answer> </body></html>


Alamo Fire 和 Swift 无法将类型“[String : String]”的值转换为预期参数类型“HTTPHeaders?”

func requestWithRetries(tag:String, url:String, maxRetry:Int = 3,expectJSONArray:Bool,completion:@escaping jsonCompletion) { var headers = [String:String]() 让 params = [String:AnyObjec...


另一个模型中的模型列表仅保存列表中所有项目中最后添加的项目

对于 (int x=0; x for (int x=0; x<listaEquipes.length; x++) { await _loadEquipe(listaEquipes[x].id.toString()); TabelaListaEquipes _reg = TabelaListaEquipes(); _reg.equipeId = listaEquipes[x].id.toString(); _reg.equipe = listaAtletaEquipe; //print (_reg.equipe![0].nome.toString()); listaEquipesGeral.add(_reg); } 此型号: class TabelaListaEquipes { String? equipeId; List<TabelaInscricoes>? equipe; TabelaListaEquipes( { this.equipeId, this.equipe}); } 现在我看到最后一个reg保存在列表的所有iten中,为什么? 这就对了: listaEquipesGeral[0].equipe == listEquipesGeral[1].equipe ...仍然添加了最后一项。为什么?? _loadEquipe 函数,它也有效,我已经测试过了, List<TabelaInscricoes> listaAtletaEquipe = []; Future<void> _loadEquipe(equipId) async { setState(() { listaAtletaEquipe.clear(); carregandoEquipe = true; }); TabelaInscricoes _result = TabelaInscricoes(); CollectionReference _dbCollection = FirebaseFirestore.instance.collection('campeonatos').doc(resultSelect.campId).collection('divisoes').doc(resultSelect.divId).collection('equipes').doc(equipId).collection('atletas'); await _dbCollection.orderBy('pos2', descending: false).get().then((QuerySnapshot querySnapshot) async { if (querySnapshot.docs.isNotEmpty) { querySnapshot.docs.forEach((element) async { _result = TabelaInscricoes.fromJson(element.data()! as Map<String, dynamic>); if (_result.campId == resultSelect.campId && _result.divId == resultSelect.divId) { _result.id = element.id; _result.filePath = ""; setState(() { listaAtletaEquipe.add(_result); }); } }); for (int x = 0; x<listaAtletaEquipe.length; x++) { for (int y = 0; y<listaAtletas.length; y++) { if (listaAtletaEquipe[x].atletaId.toString() == listaAtletas[y].id.toString()) { setState(() { listaAtletaEquipe[x].nome = listaAtletas[y].nome; listaAtletaEquipe[x].fotoNome = listaAtletas[y].fotoNome; listaAtletaEquipe[x].filePath = listaAtletas[y].filePath; listaAtletaEquipe[x].dataN = listaAtletas[y].dataN; listaAtletaEquipe[x].fone1 = listaAtletas[y].fone1; listaAtletaEquipe[x].fone2 = listaAtletas[y].fone2; listaAtletaEquipe[x].nTitulo = listaAtletas[y].nTitulo; listaAtletaEquipe[x].info = listaAtletas[y].info; listaAtletaEquipe[x].email = listaAtletas[y].email; }); } } } for (int x=0; x<listaAtletaEquipe.length; x++) { if (listaAtletaEquipe[x].fotoNome.toString().isNotEmpty) { await MyStorage.getUrl(context, "atletas/${listaAtletaEquipe[x].fotoNome.toString()}").then((value) { setState(() { listaAtletaEquipe[x].filePath = value; }); }); } } setState(() { carregandoEquipe = false; }); }else { setState(() { carregandoEquipe = false; }); } }); } AtletaEquipes 型号操作系统列表: class TabelaInscricoes{ bool? carregando = true; String? id; String? campId; String? divId; String? atletaId; String? nome_responsavel; String ?posicao; String? filePath; Uint8List? imageFile; String? usuario; String? nInscricao; String? nome; String? dataN; String? nTitulo; String? fone1; String? fone2; String? info; String? email; String? fotoNome; String? pos2; String? selected; TabelaInscricoes({ this.carregando, this.nome, this.dataN, this.nTitulo, this.fone1, this.fone2, this.info, this.email, this.id, this.campId, this.divId, this.posicao, this.nome_responsavel, this.nInscricao, this.atletaId, this.selected, this.pos2, this.fotoNome, this.filePath, this.imageFile, this.usuario}); Map<String, dynamic> toJson() => { 'campId': campId, 'divId': divId, 'atletaId': atletaId, 'nome_responsavel': nome_responsavel, 'posicao': posicao, 'usuario': usuario, 'nInscricao': nInscricao, 'pos2': pos2, 'selected': selected }; TabelaInscricoes.fromJson(Map<String, dynamic> json) : campId = json['campId'], divId = json['divId'], atletaId = json['atletaId'], nome_responsavel = json['nome_responsavel'], posicao = json['posicao'], nInscricao = json['nInscricao'], pos2 = json['pos2'], selected = json['selected'], usuario = json['usuario']; } 这里发生了什么,listaEquipesGeral 总是保存最后添加的所有项目。 我明白了,解决方案是在模型内的列表中逐项添加: for (int x=0; x<listaEquipes.length; x++) { await _loadEquipe(listaEquipes[x].id.toString()); TabelaListaEquipes _reg = TabelaListaEquipes(); _reg.equipeId = listaEquipes[x].id.toString(); _reg.equipe = []; //here above the solution, include for to put item by item, and it works for (int y = 0; y<listaAtletaEquipe.length; y++) { _reg.equipe!.add(listaAtletaEquipe[y]); } //print (_reg.equipe![0].nome.toString()); listaEquipesGeral.add(_reg); }


仅在打字稿中为泛型类型提供部分类型

我想知道是否有一种简写方式可以在打字稿中为泛型类型仅指定一些可选类型。例如,如果我有一个带有可选类型的类: 类通用类 我想知道是否有一种简写方式可以在打字稿中为泛型类型仅指定一些可选类型。例如,如果我有一个带有可选类型的类: class GenericClass<A extends Type1 = Type1, B extends Type2 = Type2, C extends Type3 = Type3> 然后我想定义一个子类,例如:class Subclass extends GenericClass<TypeB> ,这将是class Subclass extends GenericClass<Type1, TypeB, Type3>的简写,但它不起作用。相反,它尝试将 TypeB 推断为 Type1 的子类型,这会产生错误。然而,在此示例中也允许省略 Type3 并让打字稿推断它。这样的东西对我定义通用反应组件很有用,我想在其中指定状态类型,而不是道具。 我是否正确,在指定可选类型时必须提供所有前面的可选类型。或者有什么办法可以像我尝试的那样吗? 对于可选函数参数,您只需为前面的可选参数指定 undefined ,这对于泛型不起作用,但我确实尝试过,使用 void 代替,但这也不起作用。我也尝试过使用像 Subclass extends GenericClass<B = TypeB> 这样的语法,但这也不起作用。 我看到了一些用接口替换可选函数参数的建议,例如: interface Args { a?: number, b?: string, c?: any} function myFunc(Args) {} 然后可以像 myFunc({b: "value"}); 一样调用,并且避免必须执行 myFunc(undefined, "value");。这感觉像是一个糟糕的选择,但也许可以对泛型类型做这样的事情?但我不确定那会是什么样子。 我尝试的另一件事是重载像type GenericClass<B extends Type2> = GenericClass<Type1, B, Type3>这样的类型。这不起作用,除非我输入不同的名称,例如 GenericClassB TypeScript 目前不具备您正在寻找的功能,至少从 TS5.1 开始是这样。 Generic 类型参数只有在具有 defaults 时才能被省略,并且不允许跳过任何参数。有一些开放的功能请求,如果实现,可能会实现您想要的功能: 有部分类型参数推断,如microsoft/TypeScript#26242中的要求。该提案的一部分是允许使用“印记”或“占位符”类型,以便您可以编写类似 GenericClass<*, TypeB, *> 或 GenericClass<_, TypeB, _> 等内容。 还有命名类型参数,如microsoft/TypeScript#38913中的要求,您可以在其中编写GenericClass<B=TypeB>,或者根据microsoft/TypeScript#54254中的要求,您可以在其中编写类似GenericClass<B: TypeB>或可能的内容GenericClass<{B: TypeB}>。 最后,您提到的解决方法是使用单个类型参数constrained到具有所有可选属性的Args类型,除了TypeScript无法从索引访问类型推断之外,该解决方法有效;也就是说,它可以从 A 类型的值推断出 A,但不能从 T extends {a: any} 类型的值推断出 T["a"]。 microsoft/TypeScript#51612 有一个开放的功能请求可以做到这一点,但同样,它还不是该语言的一部分。 最近提到的两个问题中的一个或两个可能有希望得到解决。事实上,在 microsoft/TypeScript#53017 有一个拉取请求,它实现了最后一个,但我不知道它是否会被合并。 (microsoft/TypeScript#20126 上的一个更旧的拉取请求也实现了它,但它被放弃了。) 但在那之前您将需要使用解决方法。 不知道如何进行课程,我通常只使用type,你可以这样做: type Tuple3<a,b,c> = [a,b,c] const t3: Tuple3<number, string, string> = [3, 'apple', 'banana'] type NamedTuple2<a,b> = Tuple3<string,a,b> const namedT2: NamedTuple2<number, string> = ['fruites', 2,... 游乐场链接


NodeJS 我当前的 Google Cloud 函数名称是什么?

我想使用当前Google Cloud Function的名称来驱动一些逻辑。如何确定我的 Google Cloud Function 名称是什么?


Kotlin - 主要和次要构造函数

class SmartDevice(val 名称: String, val 类别: String) { var deviceStatus = "在线" 构造函数(名称:字符串,类别:字符串,状态代码:Int):this(名称,类别){ ...


在使用 TypeScript 进行 React 时,输入字段在“值”处给出错误

从“react”导入{SetStateAction,useState} const 登录表单 =() =>{ const [名称,setName] = useState(); const [全名,setFullname] = useState import { SetStateAction, useState } from "react" const Loginform =() =>{ const [name, setName] = useState<String | null>(); const [fullname, setFullname] = useState<String | null>(); const inputEvent =(event: { target: { value: SetStateAction< String |null | undefined >; }; })=>{ setName(event.target.value) } const Submit = ()=>{ setFullname(name) } return <> <h1>Enter Your Name </h1> <input type="text" placeholder="Enter your name" onChange={inputEvent} value={name}/> <button onClick={Submit}>Submit</button> <h1>Hi {fullname==null? "Guest" :fullname}</h1> </> } export default Loginform <input type="text" placeholder="Enter your name" onChange={inputEvent} value={name}/> 上一行中的“value”属性显示错误 这是错误详细信息: (property) React.InputHTMLAttributes<HTMLInputElement>.value?: string | number | readonly string[] | undefined Type 'String | null | undefined' is not assignable to type 'string | number | readonly string[] | undefined'. Type 'null' is not assignable to type 'string | number | readonly string[] | undefined'.ts(2322) index.d.ts(2398, 9): The expected type comes from property 'value' which is declared here on type 'DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>' 也尝试写 return as any。或者尝试添加 string[],但出现错误。 进行以下调整: 将 String 替换为 string,因为原始 Typescript 类型是小写的 (number, string, boolean, etc) TypeScript 报告此错误,因为属性值不接受 null 作为值,而是接受 undefined。将代码更新为: const [name, setName] = useState<string>() 这会使用 string 作为默认类型来初始化状态。 初始状态隐式地被视为 undefined,因为如果未显式提供,TypeScript 会将类型的默认值设置为 undefined。 为了简单起见,您不需要解构事件。使用内联函数,如下例所示: <input type="text" placeholder="Enter your name" onChange={(e) => setName(e.target.value)} value={name}/> 我使用你的代码创建了一个 CodeSanbox,它似乎只需要很少的修改就可以正常工作。 您可以在这里找到沙盒 这是我想出的代码 import { SetStateAction, useState } from "react"; const Loginform = () => { const [name, setName] = useState<string | null>(); const [fullname, setFullname] = useState<string | null>(); const inputEvent = (event: { target: { value: SetStateAction<string | null | undefined> }; }) => { setName(event.target.value); }; const Submit = () => { setFullname(name); }; return ( <div> <h1>Enter Your Name </h1> <input type="text" placeholder="Enter your name" onChange={inputEvent} value={name} /> <button onClick={Submit}>Submit</button> <h1>Hi {fullname == null ? "Guest" : fullname}</h1> </div> ); }; export default Loginform;


Julia 语法错误@kwdef,默认值为字符串

此代码会产生语法错误。我无法在 @kwdef 结构中使用默认值? @kwdef 结构 MyStruct indir::String = "./", outdir::String = "./结果", 阈值...


Azure Function Python V2 一个函数应用程序中的多个函数

我正在寻找有关在一个 Azure Function App 中为多个函数创建项目结构的指导。这是我之前读过的一篇文章 在一个 Azure Function App 中创建多个函数 有一个...


如何生成带有货币符号(例如 $)而不是货币代码(USD、EUR)的价格字符串?

这是我当前的代码: fun getMonthlyPriceString(yearlyPriceMicros: Long,currencyCode: String): String { val 格式:NumberFormat = NumberFormat.getCurrencyInstance() 格式。


如何返回内在的字符串操作类型?

要返回模板文字类型,需要返回一个模板文字: 输入 HelloSomething = `你好 ${string}` const str = '世界' 函数 sayHello(str: string): HelloSomething { 返回`...


Python 中的 AWS Lambda 函数,生成字符串流

所以我想利用这个.net代码,我在卡盘中接收响应并单独处理每个块 公共异步任务 InvokeLambdaFunctionAsync(string functionName, string pay...


使用 Azure Function 运行时和 pytest 'ModuleNotFoundError:没有名为...的模块'时出现导入问题

我的项目结构如下所示: 回购/ |--模型/api |--function/function_app.py |--函数/工具.py |--函数/__init__.py |--测试/test_function_app.py ...


无法将 Generic<string> 转换为 Generic<TArg>,即使我在检查 Generic<string> 是否可分配给 Generic<TArg>

和标题差不多。我有这个代码: if (typeof(Option).IsAssignableTo(typeof(Option))) { 返回新结果(无(),(选项)结果.GetErr(...


在 Android Studio 中找不到错误符号

String sAux=getResources().getString(R.string.ShareText); sAux+=” ”; sAux+="https://play.google.com/store/apps/details?id="; sAux+=getPackageName(); sAux+=” ”; ...


为什么 sonarqube 存在安全问题?

我有以下方法: 公共列表 getZipFileList(String fullPath) 抛出 IOException { logger.debug("====> ZipService: getZipFileList <====");


是否可以从zoned_time获取time_point?

我尝试在 std::string 中有选择地获取当地时间/UTC。 我尝试过的: (1) 获取 UTC 的 std::string 使用 std::format 可以正常工作: 自动 utc = std::chrono::system_clock::now(); std::字符串...


如何在Azure Function中获取连接字符串?

我在 Azure 云中有一个 Azure Function 和一个 PostreSQL DB。 我想从我的 Azure 函数访问连接字符串,我们将其称为 IT-PostgreSQL。 这是我的Azure功能: 命名空间


如何在 Groovy 中声明字符串数组?

如何在 Groovy 中声明字符串数组?我正在尝试如下但它抛出一个错误 def String[] osList = new String[] 行中没有数组构造函数调用的表达式: 我在做什么...


滚动时仅触发一次功能

我想在div滚动到视口时启动一个函数。我的问题是,每次我继续滚动时,该功能都会再次触发/启动。 HTML: <... 我想在 div 滚动到视口中时启动一个函数。我的问题是,每次我继续滚动时,该功能都会再次触发/启动。 HTML: <div class="box"></div> JS: $(document).ready(function() { function start() { alert("hello"); } $(window).scroll(function() { if ( $(window).scrollTop() >= $('.box').offset().top - ($(window).height() / 2)) { $(".box").addClass("green"); start(); } else { $(".box").removeClass("green"); } }); }); 总结一下:当div滚动到视口中时,应该启动“start”函数。但触发一次后就不能再触发了。 小提琴 您可以设置一个标志,例如: var started = false; function start() { if(!started) { alert("hello"); } started = true; } 演示 $(document).ready(function() { var started = 0; function start() { if(started==0) { alert("Alert only once"); } started = 1; } $(window).scroll(function() { if ( $(window).scrollTop() >= $('.box').offset().top - ($(window).height() / 2)) { $(".box").addClass("green"); start(); } else { $(".box").removeClass("green"); } }); }); *{margin:0;} .box { background: red; height: 200px; width: 100%; margin: 800px 0 800px 0; } .green { background: green; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <br /> <center> <br /> <h1>scroll down</h1> </center> <div class="box"></div> 有很多方法可以解决这个问题。您可以删除事件侦听器(因为您使用的是 jQuery,所以我将使用 on 和 off 方法): $(window).on('scroll', function() { if ( $(window).scrollTop() >= $('.box').offset().top - ($(window).height() / 2)) { $(".box").addClass("green"); start(); } else { $(".box").removeClass("green"); } $(window).off('scroll'); }); 如果你希望窗口滚动方法在启动方法满足要求后停止..你可以这样做 $(document).ready(function() { var toggleScroll = false; function start() { alert("hello"); } $(window).one("scroll", checkToggleScroll); function checkToggleScroll(){ if ( $(window).scrollTop() >= $('.box').offset().top - ($(window).height() / 2)) { $(".box").addClass("green"); toggleScroll = true; start(); } else { $(".box").removeClass("green"); } if(!toggleScroll){ $(window).one("scroll", checkToggleScroll); } } }); 当start()没有类$(".box)(在一定量的滚动后添加)时,只需运行"green"函数。 $(document).ready(function() { function start() { alert("hello"); } $(window).scroll(function() { if ($(window).scrollTop() >= $('.box').offset().top - ($(window).height() / 2)) { if (!$(".box").hasClass("green")) { $(".box").addClass("green"); start(); } } else { $(".box").removeClass("green"); } }); }); .box { background: red; height: 200px; width: 100%; margin: 800px 0 800px 0; } .green { background: green; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="box"></div>


通过更少的 Java API 调用来映射 Google 云端硬盘内容的有效方法

大家好,我有一个代码,用于列出共享驱动器中存在的文件(以便稍后下载并创建相同的文件夹路径) 目前我做这样的事情: 哈希映射 大家好,我有一个代码,用于列出共享驱动器中存在的文件(以便稍后下载并创建相同的文件夹路径) 目前我正在做这样的事情: HashMap<String, Strin> foldersPathToID = new HashMap<>(); //searching all folders first saving their IDs searchAllFoldersRecursive(folderName.trim(), driveId, foldersPathToID); //then listing files in all folders HashMap<String, List<File>> pathFile = new HashMap<>(); for (Entry<String, String> pathFolder : foldersPathToID.entrySet()) { List<File> result = search(Type.FILE, pathFolder.getValue()); if (result.size() > 0) { String targetPathFolder = pathFolder.getKey().trim(); pathFile.putIfAbsent(targetPathFolder, new ArrayList<>()); for (File file : result) { pathFile.get(targetPathFolder).add(file); } } } 递归方法在哪里: private static void searchAllFoldersRecursive(String nameFold, String id, HashMap<String, String> map) throws IOException, RefreshTokenException { map.putIfAbsent(nameFold, id); List<File> result; result = search(Type.FOLDER, id); // dig deeper if (result.size() > 0) { for (File folder : result) { searchAllFoldersRecursive(nameFold + java.io.File.separator + normalizeName(folder.getName()), folder.getId(), map); } } } 搜索功能是: private static List<com.google.api.services.drive.model.File> search(Type type, String folderId) throws IOException, RefreshTokenException { String nextPageToken = "go"; List<File> driveFolders = new ArrayList<>(); com.google.api.services.drive.Drive.Files.List request = service.files() .list() .setQ("'" + folderId + "' in parents and mimeType" + (type == Type.FOLDER ? "=" : "!=") + "'application/vnd.google-apps.folder' and trashed = false") .setPageSize(100).setFields("nextPageToken, files(id, name)"); while (nextPageToken != null && nextPageToken.length() > 0) { try { FileList result = request.execute(); driveFolders.addAll(result.getFiles()); nextPageToken = result.getNextPageToken(); request.setPageToken(nextPageToken); return driveFolders; } catch (TokenResponseException tokenError) { if (tokenError.getDetails().getError().equalsIgnoreCase("invalid_grant")) { log.err("Token no more valid removing it Please retry"); java.io.File cred = new java.io.File("./tokens/StoredCredential"); if (cred.exists()) { cred.delete(); } throw new RefreshTokenException("Creds invalid will retry re allow for the token"); } log.err("Error while geting response with token for folder id : " + folderId, tokenError); nextPageToken = null; } catch (Exception e) { log.err("Error while reading folder id : " + folderId, e); nextPageToken = null; } } return new ArrayList<>(); } 我确信有一种方法可以通过很少的 api 调用(甚至可能是一个调用?)对每个文件(使用文件夹树路径)进行正确的映射,因为在我的版本中,我花了很多时间进行调用 service.files().list().setQ("'" + folderId+ "' in parents and mimeType" + (type == Type.FOLDER ? "=" : "!=") + "'application/vnd.google-apps.folder' and trashed = false").setPageSize(100).setFields("nextPageToken, files(id, name)"); 每个子文件夹至少一次......并且递归搜索所有内容需要很长时间。最后,映射比下载本身花费的时间更多...... 我搜索了文档,也在此处搜索,但没有找到任何内容来列出具有一个库的所有驱动器调用任何想法? 我想使用专用的 java API 来获取共享 GoogleDrive 中的所有文件及其相对路径,但调用次数尽可能少。 提前感谢您的时间和答复 我建议您使用高效的数据结构和逻辑来构建文件夹树并将文件映射到其路径,如下所示 private static void mapDriveContent(String driveId) throws IOException { // HashMap to store folder ID to path mapping HashMap<String, String> idToPath = new HashMap<>(); // HashMap to store files based on their paths HashMap<String, List<File>> pathToFile = new HashMap<>(); // Fetch all files and folders in the drive List<File> allFiles = fetchAllFiles(driveId); // Build folder path mapping and organize files for (File file : allFiles) { String parentId = (file.getParents() != null && !file.getParents().isEmpty()) ? file.getParents().get(0) : null; String path = buildPath(file, parentId, idToPath); if (file.getMimeType().equals("application/vnd.google-apps.folder")) { idToPath.put(file.getId(), path); } else { pathToFile.computeIfAbsent(path, k -> new ArrayList<>()).add(file); } } // Now, pathToFile contains the mapping of paths to files // Your logic to handle these files goes here } private static List<File> fetchAllFiles(String driveId) throws IOException { // Implement fetching all files and folders here // Make sure to handle pagination if necessary // ... } private static String buildPath(File file, String parentId, HashMap<String, String> idToPath) { // Build the file path based on its parent ID and the idToPath mapping // ... }


Azure Function App 无法启动 Docker 容器,原因是“Azure.RequestFailedException:指定的资源名称包含无效字符。”

我们有一个从 Docker 映像部署的 Azure Function 应用程序。 该函数正在运行 .NET 8.0,FUNCTIONS_EXTENSION_VERSION = ~4 且 FUNCTIONS_WORKER_RUNTIME = dotnet-isolated。 该应用程序包含...


了解 std::function 的开销并捕获同步 lambda

考虑以下简单示例: #包括 #包括 #包括 #包括 #包括 #包括...


Vue 3如何获取$children的信息

这是我在 Tabs 组件中使用 VUE 2 的旧代码: 创建(){ this.tabs = this.$children; } 标签: .... 这是我在 Tabs 组件中使用 VUE 2 的旧代码: created() { this.tabs = this.$children; } 标签: <Tabs> <Tab title="tab title"> .... </Tab> <Tab title="tab title"> .... </Tab> </Tabs> VUE 3: 如何使用组合 API 获取有关 Tabs 组件中子项的一些信息?获取长度,迭代它们,并创建选项卡标题,...等?有任何想法吗? (使用组合API) 这是我现在的 Vue 3 组件。我使用 Provide 来获取子 Tab 组件中的信息。 <template> <div class="tabs"> <div class="tabs-header"> <div v-for="(tab, index) in tabs" :key="index" @click="selectTab(index)" :class="{'tab-selected': index === selectedIndex}" class="tab" > {{ tab.props.title }} </div> </div> <slot></slot> </div> </template> <script lang="ts"> import {defineComponent, reactive, provide, onMounted, onBeforeMount, toRefs, VNode} from "vue"; interface TabProps { title: string; } export default defineComponent({ name: "Tabs", setup(_, {slots}) { const state = reactive({ selectedIndex: 0, tabs: [] as VNode<TabProps>[], count: 0 }); provide("TabsProvider", state); const selectTab = (i: number) => { state.selectedIndex = i; }; onBeforeMount(() => { if (slots.default) { state.tabs = slots.default().filter((child) => child.type.name === "Tab"); } }); onMounted(() => { selectTab(0); }); return {...toRefs(state), selectTab}; } }); </script> 选项卡组件: <script lang="ts"> export default defineComponent({ name: "Tab", setup() { const index = ref(0); const isActive = ref(false); const tabs = inject("TabsProvider"); watch( () => tabs.selectedIndex, () => { isActive.value = index.value === tabs.selectedIndex; } ); onBeforeMount(() => { index.value = tabs.count; tabs.count++; isActive.value = index.value === tabs.selectedIndex; }); return {index, isActive}; } }); </script> <template> <div class="tab" v-show="isActive"> <slot></slot> </div> </template> 哦伙计们,我解决了: this.$slots.default().filter(child => child.type.name === 'Tab') 对于想要完整代码的人: 标签.vue <template> <div> <div class="tabs"> <ul> <li v-for="tab in tabs" :class="{ 'is-active': tab.isActive }"> <a :href="tab.href" @click="selectTab(tab)">{{ tab.name }}</a> </li> </ul> </div> <div class="tabs-details"> <slot></slot> </div> </div> </template> <script> export default { name: "Tabs", data() { return {tabs: [] }; }, created() { }, methods: { selectTab(selectedTab) { this.tabs.forEach(tab => { tab.isActive = (tab.name == selectedTab.name); }); } } } </script> <style scoped> </style> 标签.vue <template> <div v-show="isActive"><slot></slot></div> </template> <script> export default { name: "Tab", props: { name: { required: true }, selected: { default: false} }, data() { return { isActive: false }; }, computed: { href() { return '#' + this.name.toLowerCase().replace(/ /g, '-'); } }, mounted() { this.isActive = this.selected; }, created() { this.$parent.tabs.push(this); }, } </script> <style scoped> </style> 应用程序.js <template> <Tabs> <Tab :selected="true" :name="'a'"> aa </Tab> <Tab :name="'b'"> bb </Tab> <Tab :name="'c'"> cc </Tab> </Tabs> <template/> 我扫描子元素的解决方案(在对 vue 代码进行大量筛选之后)是这样的。 export function findChildren(parent, matcher) { const found = []; const root = parent.$.subTree; walk(root, child => { if (!matcher || matcher.test(child.$options.name)) { found.push(child); } }); return found; } function walk(vnode, cb) { if (!vnode) return; if (vnode.component) { const proxy = vnode.component.proxy; if (proxy) cb(vnode.component.proxy); walk(vnode.component.subTree, cb); } else if (vnode.shapeFlag & 16) { const vnodes = vnode.children; for (let i = 0; i < vnodes.length; i++) { walk(vnodes[i], cb); } } } 这将返回子组件。我对此的用途是我有一些通用的对话框处理代码,用于搜索子表单元素组件以咨询其有效性状态。 const found = findChildren(this, /^(OSelect|OInput|OInputitems)$/); const invalid = found.filter(input => !input.checkHtml5Validity()); 如果你复制粘贴与我相同的代码 然后只需向“选项卡”组件添加一个创建的方法,该方法将自身添加到其父级的选项卡数组中 created() { this.$parent.tabs.push(this); }, 使用脚本设置语法,您可以使用useSlots:https://vuejs.org/api/sfc-script-setup.html#useslots-useattrs <script setup> import { useSlots, ref, computed } from 'vue'; const props = defineProps({ perPage: { type: Number, required: true, }, }); const slots = useSlots(); const amountToShow = ref(props.perPage); const totalChildrenCount = computed(() => slots.default()[0].children.length); const childrenToShow = computed(() => slots.default()[0].children.slice(0, amountToShow.value)); </script> <template> <component :is="child" v-for="(child, index) in childrenToShow" :key="`show-more-${child.key}-${index}`" ></component> </template> 我对 Ingrid Oberbüchler 的组件做了一个小改进,因为它不支持热重载/动态选项卡。 在 Tab.vue 中: onBeforeMount(() => { // ... }) onBeforeUnmount(() => { tabs.count-- }) 在 Tabs.vue 中: const selectTab = // ... // ... watch( () => state.count, () => { if (slots.default) { state.tabs = slots.default().filter((child) => child.type.name === "Tab") } } ) 我也遇到了同样的问题,在做了很多研究并问自己为什么他们删除了$children之后,我发现他们创建了一个更好、更优雅的替代方案。 这是关于动态组件的。 (<component: is =" currentTabComponent "> </component>). 我在这里找到的信息: https://v3.vuejs.org/guide/component-basics.html#dynamic-components 希望这对你有用,向大家问好!! 我发现这个更新的 Vue3 教程使用 Vue 插槽构建可重用的选项卡组件对于与我相关的解释非常有帮助。 它使用 ref、provide 和ject 来替换我遇到同样问题的this.tabs = this.$children;。 我一直在遵循我最初发现的构建选项卡组件(Vue2)的教程的早期版本创建您自己的可重用 Vue 选项卡组件。 根据 Vue 文档,假设您在 Tabs 组件下有一个默认插槽,您可以直接在模板中访问该插槽的子级,如下所示: // Tabs component <template> <div v-if="$slots && $slots.default && $slots.default()[0]" class="tabs-container"> <button v-for="(tab, index) in getTabs($slots.default()[0].children)" :key="index" :class="{ active: modelValue === index }" @click="$emit('update:model-value', index)" > <span> {{ tab.props.title }} </span> </button> </div> <slot></slot> </template> <script setup> defineProps({ modelValue: Number }) defineEmits(['update:model-value']) const getTabs = tabs => { if (Array.isArray(tabs)) { return tabs.filter(tab => tab.type.name === 'Tab') } else { return [] } </script> <style> ... </style> 并且 Tab 组件可能类似于: // Tab component <template> <div v-show="active"> <slot></slot> </div> </template> <script> export default { name: 'Tab' } </script> <script setup> defineProps({ active: Boolean, title: String }) </script> 实现应类似于以下内容(考虑一组对象,每个部分一个,带有 title 和 component): ... <tabs v-model="active"> <tab v-for="(section, index) in sections" :key="index" :title="section.title" :active="index === active" > <component :is="section.component" ></component> </app-tab> </app-tabs> ... <script setup> import { ref } from 'vue' const active = ref(0) </script> 另一种方法是使用 useSlots,如 Vue 文档(上面的链接)中所述。 在 3.x 中,$children 属性已被删除并且不再受支持。相反,如果您需要访问子组件实例,他们建议使用 $refs。作为数组 https://v3-migration.vuejs.org/writing-changes/children.html#_2-x-syntax 在 3.x 版本中,$children 已被删除且不再受支持。使用 ref 访问子实例。 <script setup> import { ref, onMounted } from 'vue' import ChildComponent from './ChildComponent .vue' const child = ref(null) onMounted(() => { console.log(child.value) // log an instance of <Child /> }) </script> <template> <ChildComponent ref="child" /> </template> 详细信息:https://vuejs.org/guide/essentials/template-refs.html#template-refs 基于@Urkle的回答: /** * walks a node down * @param vnode * @param cb */ export function walk(vnode, cb) { if (!vnode) return; if (vnode.component) { const proxy = vnode.component.proxy; if (proxy) cb(vnode.component.proxy); walk(vnode.component.subTree, cb); } else if (vnode.shapeFlag & 16) { const vnodes = vnode.children; for (let i = 0; i < vnodes.length; i++) { walk(vnodes[i], cb); } } } 除了已接受的答案之外: 而不是 this.$root.$children.forEach(component => {}) 写 walk(this.$root, component => {}) 这就是我让它为我工作的方式。


C++:将 std::string 分配给缓冲区数组

在处理必须与 C 代码互操作的代码时,我经常遇到这个问题,其中有一个 std::string ,您需要将其内容复制到普通的 char 缓冲区,如下所示: 结构体T {...


新的 Azure Function App 处理已由另一个 Function App 处理过的 Blob

我有以下情况。我有一个在 Windows 应用服务计划上运行的功能。该函数处理 blob。该函数具有默认的 LogsAndContainerScan 触发器。现在过了一段时间我...


如何解决 Firebase Cloud Function 未在 SSR 的“/workspace/.next”中找到 Next.js 生产版本?

我之前问过这个问题,并且仍在为这个问题苦苦挣扎;谁能帮我解决这个问题: SSR Next.js 应用程序的 Firebase Cloud Function 未在...中找到生产版本


背景颜色未正确应用

我有这个自定义控件。 公共类面板:ContentView { 公共静态只读 BindableProperty CaptionProperty = BindableProperty.CreateAttached(nameof(Caption), typeof(string),


根据输入参数获取列表

我在Java中有以下方法: 公共列表getList(字符串str,类clazz){ List lst = new ArrayList<>(); String[] arr = str.split(",&quo...


flutter中如何区分网络图片和文件图片?

我很难区分网络图像和文件图像。 putImage(图像){ if(image.runtimeType == String){ // if(image.contains('http')){ imageInProfile = NetworkIm...


将 YAML 文件注入构造函数

我有这个 YAML 文件 src/main/resources/foo.yml: 酒吧: - 你好 - 世界 巴兹: - 洛雷姆 - ipsum 这个组件: @成分 公共类我的组件{ 公共我的组件(地图 我有这个 YAML 文件 src/main/resources/foo.yml: bar: - hello - world baz: - lorem - ipsum 这个组件: @Component public class MyComponent { public MyComponent(Map<String, List<String>> foo) { // foo.get("bar") } } 使用 Spring Boot 2.7,是否可以将配置按原样(自己的文件,无前缀,无类)注入到构造函数中? 你可以这样做 @Configuration public class MyConfiguration { @Bean public Map<String, Object> foo(@Value("classpath:foo.yaml") Resource yaml) { Yaml yaml = new Yaml(); return yaml.load(yaml.getInputStream()); } } @Component public class MyComponent { public MyComponent(@Qualifier("foo") Map<String, Object> foo) { ... } }


闪亮的server.R无法读取全局变量

./app 中的两个文件 ui.R 图书馆(闪亮) 一个<- 1 ui <- fluidPage( textOutput("test") ) server.R server <- function(input, output) { output$test <- renderText({ a ...


如果需要很长时间,如何在Javascript中设置稍后执行的函数?

函数等待() { 让 a = Date.now() while (Date.now() - 一个 < 3000) { //loop } console.log('waiting ends...') } function start(){ console.log('starts...') wait() }


如何将yield return与microsoft graph api v5 PageIterator一起使用

目前我正在使用 AsyncEnumerable 从 Graph API 获取组成员 公共异步 IAsyncEnumerable LoadGroupMembers(string GroupId) { if (graphClient == null) th...


为什么 Odoo 17 没有在 <notebook> 中为我的字段渲染标签?

我正在运行有关 Odoo 17 开发的教程,并为第 7 章中的练习创建了以下代码: 我正在运行有关 Odoo 17 开发的教程,并且我为第 7 章中的练习创建了此代码: <record id="estate_view_form" model="ir.ui.view"> <field name="name">estate.property.form</field> <field name="model">estate.property</field> <field name="arch" type="xml"> <form string="Estate Property" create="True"> <sheet> <group string="Info"> <field name="name" /> <field name="description" /> </group> <group string="Location"> <field name="postcode" /> </group> <notebook> <page string="Specs"> <field name="facades" /> <field name="garage" /> </page> </notebook> </sheet> </form> </field> </record> 它可以工作,但 <notebook> 中字段的标签未呈现。我尝试添加 string 属性,但这不起作用。 <notebook> 上的 文档没有提及任何有关此行为的信息。 IIRC 自从我使用的每个版本(6.1+)以来,你必须在 group 周围有一个 field 才能自动获取标签。


地图<String, Repository>意外行为

我正在尝试定义一个Map来映射多个JPA存储库。这是我的代码 @服务 @AllArgsConstructor 公共类 MyDataTablesService { 私人决赛


将_map<string,dynmic>转换为flutter中的模态

我有以下记录来自API { 成功:真实 状态:200, 令牌:“...”, 消息:“您已登录” 用户:{id:1,名字:“..”,名字:“....


将_map<string,dynmic>转换为flutter中的模型

我有以下记录来自API { 成功:真实 状态:200, 令牌:“...”, 消息:“您已登录” 用户:{id:1,名字:“..”,名字:“....


购物车变换功能

我想使用购物车转换创建扩展包。首先,我复制了“input.grqphql”和“index.ts”,如下所示:[PR (https://github.com/Shopify/function-examples/pull/276)] 之后,我...


© www.soinside.com 2019 - 2024. All rights reserved.