data: () => ({
map: {
activeMarkerIndex: null,
markerIconImages: [ MAP_MARKER_DEFAULT, MAP_MARKER_ACTIVE ],
...<ymap-marker
v-for="(n, i) in markers"
:icon="{
...map.markerIcon,
imageHref: map.markerIconImages[+(map.activeMarkerIndex === i)],
}"
@mouseenter="map.activeMarkerIndex = i"
@mouseleave="map.activeMarkerIndex = null"
...<li
v-for="(n, i) in objects"
@mouseenter="map.activeMarkerIndex = i"
@mouseleave="map.activeMarkerIndex = null"
...
$(document).click('.e-1', function(event) { console.log(event.target) });
$(document).on('click', '.e-1', function(e) {
console.log(e.currentTarget);
});
updated() { this.$refs.scroll.addEventListener('wheel', this.fadeOut); },
v-if ложно, элемента нет. Соответственно, в $refs.scroll вместо ссылки на несуществующий элемент пишется null, и вы пытаетесь обратиться к свойству этого null, чего делать не следует - у null никаких свойств нет и быть не может, подобные обращения заканчиваются ошибками вот как та, что получили вы.
Отследить переназначение локальных переменных <...> не получится, такого механизма просто нет в JavaScript. Можно лишь отслеживать изменения свойств объектов.
copyDB = будет copyDB.value =), или же удалять существующие элементы массива, и добавлять новые:copyDB.splice(0, copyDB.length, ...addFlags(props.items));
не передаются данные в router-link
Если же сделать корзину на одной странице с каталогом, то все прекрасно записывается в массив корзины.
router-link сделайте кнопку, по клику на которую сразу будет вызываться соответствующее действие или мутация.router-link передать в компонент корзины массив добавленных в неё товаров. Если так - не надо ничего передавать, пусть компонент корзины забирает данные сразу из vuex.
'*' в качестве результата, реально вы выдаёте '*\n'..join('\n'). Ну и ещё пробелов не хватает после звёздочек.const christmasTree = length =>
Array.from({ length }, (n, i) => (
n = ' '.repeat(length - i - 1),
n + '*'.repeat(i * 2 + 1) + n
)).join('\n');
const random = arr => arr[Math.random() * arr.length | 0];const item = random(random(Object.values(state.themes)));const item = random(Object.values(state.themes).flat());function weightedRandom(arr, key = () => 1) {
const val = key instanceof Function ? key : n => n[key];
const max = arr.reduce((acc, n) => acc + val(n), 0);
return () => {
let rand = Math.random() * max;
return arr.find(n => (rand -= val(n)) < 0);
};
}const randomArr = weightedRandom(Object.values(state.themes), 'length');
// ...
const item = random(randomArr());
<option v-for="item in info"> {{ item.fieldTypes.geo }} </option>
fieldTypes.geo не уникальны, option'ы тоже будут повторяться. Зачем это? Не надо. Делаем вычисляемое свойство, представляющее уникальные значение, и используем при создании option'ов его:computed: {
uniqueGeo() {
return [...new Set(this.info.map(n => n.fieldTypes.geo))];
},
...<option v-for="n in uniqueGeo">{{ n }}</option>computed: {
filteredOffers() {
const vacancy = this.searchVacancyName.toUpperCase();
const geo = this.searchGeo;
return this.info.filter(n => (
(!vacancy || n.fieldTypes.vacancyName.toUpperCase().includes(vacancy)) &&
(!geo || n.fieldTypes.geo === geo)
));
},
...
const elements = Array.prototype.filter.call(
document.querySelectorAll('.green'),
(n, i, a) => n.nextElementSibling !== a[i + 1]
);'.green + .green', или при фильтрации дополнительно проверяйте, что n.previousElementSibling === a[i - 1].
str.split('/').pop()
// или
str.match(/[^\/]+$/)[0]
// или
str.replace(/.*\//, '')
// или
str.slice(str.lastIndexOf('/') + 1)
// или
Array.from(str).reduce((acc, n) => n === '/' ? '' : acc + n, '')
// или
[...str].filter((n, i, a) => !a.includes('/', i)).join('')
function Card(props) {
return (
<div>
{props.children}
</div>
);
}
function App() {
return (
<div>
<Card />
<Card>
<CircleTopik />
</Card>
<Card />
</div>
);
}function Card({ showCircle }) {
return (
<div>
{showCircle ? <CircleTopik /> : null}
</div>
);
}
function App() {
return (
<div>
<Card />
<Card showCircle />
<Card />
</div>
);
}
React.memo затрагивает только изменения пропсов. Если функциональный компонент обёрнут в React.memo и использует useState, useReducer или useContext, он будет повторно рендериться при изменении состояния или контекста.
const itemSelector = '.header';
const buttonSelector = `${itemSelector} .delete_block`;document.querySelectorAll(buttonSelector).forEach(function(n) {
n.addEventListener('click', this);
}, ({ currentTarget: t }) => {
while (!(t = t.parentNode).matches(itemSelector)) ;
t.replaceWith();
});
// или
document.addEventListener('click', e => e
.target
.closest(buttonSelector)
?.closest(itemSelector)
.remove()
);
import re
def has_consecutive_characters(s, count):
return bool(re.search(rf'([\dA-Z])\1{{{count - 1}}}', s, re.IGNORECASE))
arr = [
'PAaAssword',
'Paaaassword',
'P111ssword',
'Password',
]
print([ has_consecutive_characters(n, 3) for n in arr ])
function merge(key, ...arrs) {
const getKey = key instanceof Function ? key : n => n[key];
const result = new Map;
arrs.forEach(arr => arr.forEach(n => {
const k = getKey(n);
result.set(k, Object.assign(result.get(k) ?? {}, n));
}));
return [...result.values()];
}const result = merge('id', arr1, arr2, arr3);.
const getTruthyKeys = obj =>
Object
.entries(obj)
.filter(n => n[1])
.map(n => n[0]);for([key, value] of Object.entries(item)) {const obj = new Proxy({
a: 0,
b: 1,
c: 2,
}, {
get: () => Math.round(Math.random()),
});console.log(Array.from({ length: 10 }, () => getTruthyKeys(obj)));
<button :disabled="!данные" @click="onClick">