попытался решить все через рекурсию
const createTree = (data, idKey, parentKey, parentId) =>
data.reduce((acc, n) => (parentId === n[parentKey] && acc.push({
...n,
children: createTree(data, idKey, parentKey, n[idKey]),
}), acc), []);
const tree = createTree(data, 'id', 'parentId', null);
function createTree(data, idKey, parentKey) {
const tree = Object.fromEntries(data.map(n => [ n[idKey], { ...n, children: [] } ]));
return Object
.values(tree)
.filter(n => !(tree[n[parentKey]] && tree[n[parentKey]].children.push(n)));
}
const tree = createTree(data, 'id', 'parentId');
передавать параметры <...> оставив в computed
methods: {
filterHeroes(attr) {
const s = this.searchHeroesString.toLowerCase();
return this.heroes.filter(n => n.hero_attribute === attr && n.name.toLowerCase().includes(s));
},
data: () => ({
active: false,
}),
created() {
const onClick = e => this.active = this.$refs.block.contains(e.target) && this.active;
document.addEventListener('click', onClick);
this.$on('hook:beforeDestroy', () => document.removeEventListener('click', onClick));
},
<button @click.stop="active = !active">click me</button>
<div :class="{ active }" ref="block">hello, world!!</div>
state: {
opened: null,
...
<Trigger :block="block">
props: [ 'block' ],
computed: mapState([ 'opened' ]),
:class="{ 'active' : block === opened }"
@click="toggleNav(block)"
toggleNav(state, block) {
state.opened = state.opened === block ? null : block;
},
state.opened = block
(название мутации в этом случае конечно следует поменять).closeSidebarPanel(state) {
state.opened = null;
},
isPanelOpen(state) {
return !!state.opened;
},
<span v-if="isPanelOpen">{{ $store.state.opened.bName }}</span>
<slot :block="$store.state.opened"></slot>
<template #default="{ block }">
<div class="sidebar-panel-settings">
<div class="setting-block">
{{ block.bName }}
</div>
</div>
</template>
array.reduceRight((acc, n) => ({ ...n, children: [ ...n.children, acc ] }), { ...obj })
{this.state.image}
<img src={this.props.items[this.state.image].img} />
<App />
<App items={items} />
const isEmpty = [...inputs].some(n => !n.value);
// или
const isEmpty = !Array.prototype.every.call(inputs, n => n.value);
// или
let isEmpty = false;
for (const n of inputs) {
if (!n.value) {
isEmpty = true;
break;
}
}
// или
let isEmpty = false;
for (let i = -1; ++i < inputs.length && !(isEmpty = !inputs[i].value);) ;
// или
const isEmpty = (function isEmpty(i) {
return i < inputs.length && (!inputs[i].value || isEmpty(-~i));
})(0);
const grouped = Object.entries(list.reduce((acc, n) => (
(acc[n.part] = acc[n.part] || []).push(n.title),
acc
), {}));
document.body.insertAdjacentHTML('beforeend', grouped
.map(([ k, v ]) => `<div>${k}</div>${v.map(n => `<div>${n}</div>`).join('')}`)
.join('')
);
document.body.append(...grouped.flat(2).map(n => {
const div = document.createElement('div');
div.innerText = n;
return div;
}));
const ids = [ 10, 13, 15 ];
.$(ids.map(n => `[data-property-id-row="${n}"]`).join(', ')).hide();
const elems = document.querySelectorAll(ids.map(n => `[data-property-id-row="${n}"]`));
for (let i = 0; i < elems.length; i++) {
elems[i].style.display = 'none';
}
document.querySelectorAll('.form-group').forEach(function(n) {
n.hidden = this.has(Number(n.getAttribute('data-property-id-row')));
}, new Set(ids));
.hidden {
display: none;
}
for (const n of document.getElementsByClassName('form-group')) {
n.classList.toggle('hidden', ids.includes(+n.dataset.propertyIdRow));
}
<select v-model="selected">
<option v-for="n in deliveryPrice" :value="n">{{ n.city }}</option>
</select>
<div v-if="selected">
<div>{{ selected.city }}</div>
<div>{{ selected.priceFrom }}</div>
</div>
[object Object]
, отображаемый в качестве value в разметке, то v-model пусть по-прежнему с примитивными значениями работает, а выбранный объект оформляем как computed свойство:<select v-model="city">
<option v-for="n in deliveryPrice">{{ n.city }}</option>
</select>
computed: {
selected() {
return this.deliveryPrice.find(n => n.city === this.city);
},
},
<select v-model="selectedIndex">
<option v-for="(n, i) in deliveryPrice" :value="i">{{ n.city }}</option>
</select>
data: () => ({
selectedIndex: -1,
}),
computed: {
selected() {
return this.deliveryPrice[this.selectedIndex];
},
},
let index = -1;
setInterval(() => {
index = (index + 1) % array.length;
console.log(array[index]);
}, 500);
Показалось будет неудобно юзать в Вью компоненте. Мне надо при наведении мышки показывать по кругу картинки из массива и останавливать при убирании мышки.
<div
@mouseenter="установитьИнтервал"
@mouseleave="сброситьИнтервал"
>
methods: {
установитьИнтервал() {
this.interval = setInterval(() => { ... }, 666);
},
сброситьИнтервал() {
clearInterval(this.interval);
},
},
function App() {
const [ values, setValues ] = useState(Array(10).fill(''));
const onChange = ({ target: t }) => {
const index = +t.dataset.index;
const value = t.value;
setValues(values.map((n, i) => i === index ? value : n));
if (index < values.length - 1 && value) {
inputRefs.current[index + 1].focus();
inputRefs.current[index + 1].select();
}
};
const inputRefs = useRef([]);
return (
<div>
{values.map((n, i) => (
<div>
<input
value={n}
data-index={i}
onChange={onChange}
ref={input => inputRefs.current[i] = input}
maxLength="1"
/>
</div>
))}
</div>
);
}
$("#changeCityInput").bind("keyup change",
$('#changeCityInput').on('input',
const checked = Array.from(document.querySelectorAll('.btn:checked'), n => n.value);
const filtered = arr.filter(n => checked.includes(n));