简体   繁体   English

在原生 JS 组件之间传递数据

[英]Passing data between vanilla JS components

Let's say we have an app that have of 2 components - an input that takes numbers and a range slider.假设我们有一个包含 2 个组件的应用程序 - 一个输入数字和一个范围 slider。 When value in the input component is updated, the slider is set to that value too, and vice versa.当输入组件中的值更新时,slider 也会设置为该值,反之亦然。 What is the best approach to do this app in vanillaJs without using React?在不使用 React 的情况下在 vanillaJs 中执行此应用程序的最佳方法是什么? If I create 2 classes, how do I reactively update the state in them and how do I store these shared state?如果我创建 2 个类,我如何反应性地更新其中的 state 以及如何存储这些共享的 state?

There is really no need for classes or shared state.真的不需要类或共享 state。 You can just use a simple event handler on each element:您可以在每个元素上使用一个简单的事件处理程序:

 var shared = document.querySelectorAll(".shared"); shared.forEach(function(el) { el.addEventListener("input", function(e) { shared.forEach(function(el) { el.value = e.target.value; }); }); });
 <input type="text" class="shared" value="50"> <input type="range" class="shared" value="50">

Maybe something like this?也许是这样的?

 const $number = document.querySelector('.number'), $slider = document.querySelector('.slider'); $number.addEventListener('change', () => { $slider.value = $number.value; }) $slider.addEventListener('input', () => { $number.value = $slider.value; });
 <input type="number" class="number" value="1" /> <input type="range" class="slider" max="100" min="1" step="1" value="1" />

Using 'input' for the range, it will update the.number while moving the bar.对范围使用“输入”,它将在移动条时更新.number。

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

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