data: () => ({
status: '',
...
computed: {
statuses() {
return [...new Set(this.characters.map(n => n.status))];
},
...
<select v-model="status">
<option value="">< ALL ></option>
<option v-for="n in statuses">{{ n }}</option>
</select>
computed: {
filteredCharacters() {
const search = this.search.toLowerCase();
const status = this.status;
return this.characters.filter(n => (
(!search || n.name.toLowerCase().includes(search)) &&
(!status || status === n.status)
));
},
...
const getRepetition = (arr, repeated) => Array
.from(arr.reduce((acc, n) => acc.set(n, -~acc.get(n)), new Map))
.reduce((acc, n) => (n[1] === repeated && acc.push(n[0]), acc), []);
function getRepetition(arr, repeated) {
const result = [];
const count = {};
for (const n of arr) {
if (!count.hasOwnProperty(n)) {
count[n] = 0;
}
count[n]++;
}
for (const n in count) {
if (count[n] === repeated) {
result.push(+n);
}
}
return result;
}
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, он будет повторно рендериться при изменении состояния или контекста.