Отследить переназначение локальных переменных <...> не получится, такого механизма просто нет в 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, он будет повторно рендериться при изменении состояния или контекста.
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 ])
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">
computed: {
model() {
return new Proxy(Object.fromEntries(this.obj2.map(n => [ n.model, null ])), {
get: (target, prop) => typeof prop === 'string'
? prop.split('.').reduce((p, c) => p?.[c], this.obj)
: target[prop],
set: (target, prop, value) => {
const keys = prop.split('.');
const key = keys.pop();
const obj = keys.reduce((p, c) => (!p.hasOwnProperty(c) && this.$set(p, c, {}), p[c]), this.obj);
this.$set(obj, key, value);
return true;
},
});
},
},
<div v-for="(v, k) in model">
<input v-model="model[k]">
</div>
computed: {
model() {
return this.obj2.map(n => {
const keys = n.model.split('.');
const key = keys.pop();
const obj = keys.reduce((p, c) => p?.[c], this.obj);
return obj && { obj, key };
}).filter(Boolean);
},
},
<div v-for="n in model">
<input v-model="n.obj[n.key]">
</div>
li:not(:first-child, :last-child)
li:not(:first-child):not(:last-child)
li {
/* тут стили для всех элементов */
}
li:first-child,
li:last-child {
/* здесь сбрасываете стили, установленные выше */
}
const replaceValues = (val, test, replacer) =>
val instanceof Array
? val.map(n => replaceValues(n, test, replacer))
: val instanceof Object
? Object.fromEntries(Object
.entries(val)
.map(([ k, v ]) => [
k,
test(k, v)
? replacer(v)
: replaceValues(v, test, replacer)
])
)
: val;
const newData = replaceValues(
data,
k => k.includes('Date'),
v => v.replace(/(\d+)-(\d+)-/, '$2.$1.')
);
получить массив
Object.values
. присвоить первому массиву значения второго только без первого элемента