Scroll down when clicked with Vue.js - javascript

What I want to do is that when the user clicks on an article, it scrolls down to a sibling section. Code looks something like this.
<template>
<article #click="handleCardClick" class="text-center mr-8 mb-12 cursor-pointer hover:opacity-50 w-1/5">
<picture class="flex justify-center items-center mb-4 w-full" style="height: 320px">
<img :src="source" :alt="imgAlt" class="shadow-md" style="" />
</picture>
<h4 class="font-bold mb-1">{{ title }}</h4>
<h6 class="text-sm text-gray-600">{{ tags.length > 0 ? tags[0].name : '' }}</h6>
</article>
</template>
<script>
import { mapActions, mapState } from 'vuex';
export default {
props: {
title: {
type: String,
required: true,
},
},
computed: {
...mapState({
previewIndex: state => state.templates.hasTemplate
}),
},
methods: {
...mapActions({
setActiveTemplate: 'templates/setActive',
setPreview: 'templates/setPreview',
removePreview: 'templates/removePreview',
}),
handleCardClick () {
this.setActiveTemplate(this.template);
this.selectTemplate(this.pos);
},
}
}
</script>
And the other file looks like this
<template>
<section v-if="template" class="flex justify-between w-full pt-10 pl-10 pr-5 pb-12 relative border-b border-t border-black my-4" style="height: 75vh">
<article class="flex flex-col justify-between" style="width: 25%">
<button #click="changeSection('invite')" class="h-1/3 pb-4">
<picture class="h-full w-full flex justify-center items-center bg-gray-100">
<img :src="template.url || ''" class="bg-gray-200 shadow-lg" style="min-height: 20px; min-width: 20px; height:80%" alt="Preview de la invitacion">
</picture>
</button>
</article>
</section>
</template>
I'm a bit new to Vue, so maybe it's really simple and I just can't find how to do it :) Thanks in advance!

You only need to assign a reference ref to each article and then build a method to go to any of your referenced articles:
<article #click="goto('art1')">Go to article 1</article>
For earch sibiling declare it's reference so you can call them on the goto method
<article ref="art1">
Article 1
</article>
Declare the goto method, it has a parameter, the reference of where you want to go.
methods: {
goto(refName) {
var element = this.$refs[refName];
var top = element.offsetTop;
window.scrollTo(0, top);
}
},
And this is it.
If you have the click action inside a child component then you'll have to use $emit to perform the click action on the parent, here is an example following the above:
Parent
<template>
<Article #scrollto="goto"></Article>
<Section ref="art1">
...
</Section>
</template>
<script>
import Article from "./article";
import Section from "./section";
export default {
methods: {
goto(refName) {
var element = this.$refs[refName];
var top = element.offsetTop;
window.scrollTo(0, top);
}
}
}
</script>
Article.vue
<template>
<div>
<button #click="$emit("scrollto", 'art1')">
Go to the Article!
</button>
</div>
</template>
Documentation about vue ref function
Documentation about window.scrollTo function

Related

Cannot read properties of undefined when in React component but works fine when in getStaticProps function

I'm trying to create a blog with Node.js, React and graphql. I'm new to all those technologies (including Java-/Typescript itself). I'd greatly appreciate your help.
Currently I'm stuck getting the data of my articles to show.
In the function getStaticProps I can read the data of my graphql response fine.
But when I pass that data as a parameter to the React component (as getStaticProps provides that data during build-time) I can't access that data anymore and get the error message "TypeError: Cannot read properties of undefined (reading 'articles')".
Below is my code:
import {GetStaticProps} from "next";
import {serverSideTranslations} from "next-i18next/serverSideTranslations";
import {ssrGetBlog} from "../../generated/page";
// #ts-ignore implicitly has any type
export default function Index(data) {
console.log(data.attributes) //TypeError: Cannot read properties of undefined (reading 'articles')
// below in getStaticProps this worked!?
return (
<div className="relative bg-gray-50 px-4 pt-16 pb-20 sm:px-6 lg:px-8 lg:pt-24 lg:pb-28">
<div className="absolute inset-0">
<div className="h-1/3 bg-white sm:h-2/3"/>
</div>
<div className="relative mx-auto max-w-7xl">
<div className="text-center">
<h2 className="text-3xl font-bold tracking-tight text-gray-900 sm:text-4xl">
{data.blogHeading}
</h2>
<p className="mx-auto mt-3 max-w-2xl text-xl text-gray-500 sm:mt-4">
{data.blogDescription}
</p>
</div>
<div className="mx-auto mt-12 grid max-w-lg gap-5 lg:max-w-none lg:grid-cols-3">
{data.attributes.articles.data.map((article) => (
<div
key={article.attributes.title}
className="flex flex-col overflow-hidden rounded-lg shadow-lg"
>
<div className="flex-shrink-0">
<img
className="h-48 w-full object-cover"
src={article.attributes.articleImg.data.attributes.url}
alt=""
/>
</div>
<div className="flex flex-1 flex-col justify-between bg-white p-6">
<div className="flex-1">
<p className="text-sm font-medium text-indigo-600">
<a href={"not implemented: article.attributes.articleCategory.data.attributes.slug"} className="hover:underline">
{"none existent: article.attributes.articleCategory.data.attributes.categoryName"}
</a>
</p>
<a href={article.attributes.slug} className="mt-2 block">
<p className="text-xl font-semibold text-gray-900">
{article.attributes.title}
</p>
<p className="mt-3 text-base text-gray-500">
{article.attributes.shortDescription}
</p>
</a>
</div>
<div className="mt-6 flex items-center">
<div className="flex-shrink-0">
<a href={"not implemented: article.attributes.author.href"}>
<span className="sr-only">{"not implemented: article.author.authorName"}</span>
<img
className="h-10 w-10 rounded-full"
src={"not implemented: article.attributes.author.authorImg"}
alt=""
/>
</a>
</div>
<div className="ml-3">
<p className="text-sm font-medium text-gray-900">
<a href={"not implemented: article.attributes.author.authorUrl"} className="hover:underline">
{"not implemented: article.attributes.author.name"}
</a>
</p>
<div className="flex space-x-1 text-sm text-gray-500">
<time dateTime={article.attributes.publishedOn}>{article.attributes.publishedOn}</time>
<span aria-hidden="true">·</span>
<span>{"not implemented: article.attributes.readingTime"} read</span>
</div>
</div>
</div>
</div>
</div>
))}
</div>
</div>
</div>
);
}
export const getStaticProps: GetStaticProps = async (context) => {
const {locale} = context;
// #ts-ignore
const blogQuery = await ssrGetBlog.getServerPage({}, context);
const data = blogQuery.props.data?.blog?.data; //props.data?.blog?.data?.attributes;
//console.log(data); // works fine
//console.log(data.attributes.articles.data[0]); // works fine
return {
props: {
data,
...(await serverSideTranslations(locale || "", ["common"])),
},
};
};
Try this, maybe you're not accessing the component's props properly
export default function Index(props) {
console.log(props.data.attributes)
}
or
export default function Index({ data }) {
console.log(data.attributes)
}
export const getStaticProps: GetStaticProps = async (context) => {
const {locale} = context;
// #ts-ignore
const blogQuery = await ssrGetBlog.getServerPage({}, context);
const data = blogQuery.props.data?.blog?.data; //props.data?.blog?.data?.attributes;
//console.log(data); // works fine
//console.log(data.attributes.articles.data[0]); // works fine
const comething = await serverSideTranslations(locale || "", ["common"])
return {
props: {
data,
...comething,
},
};
};
Try this maybe?

How to set up Vue 3 parent component to emit event to child component

I am attempting to set up a button in a Vue 3 Tailwind parent component to trigger a HeadlessUI transition event in a child component. My goal is to enable the button in the parent to emit an event, while the child component "watches" for the event before triggering the transition event as part of the callback function in the watch. So far, I have the parent component set up to trigger the emit, while the child component is set up to watch for the "transition" event. However, the event is not being executed. I'm afraid I don't have the watch in the child component set up correctly, so as to watch for the button click in the parent component. How can I go about enabling the child component to watch for the click of the button in the parent component?
Here is my code so far:
Parent:
<!-- This example requires Tailwind CSS v2.0+ -->
<template>
<div class="min-h-full">
<Disclosure as="nav" class="bg-gray-800">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex items-center justify-between h-16">
<div class="flex items-center">
<div class="hidden md:block">
<div class="ml-10 flex items-baseline space-x-4">
<button type="button" #click="transition" class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800">Click to transition</button>
</div>
</div>
</div>
</div>
</div>
</Disclosure>
<main>
<div class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
<div class="px-4 py-6 sm:px-0">
<HelloWorld :event="transition" />
</div>
</div>
</main>
</div>
</template>
<script setup>
import { Disclosure, DisclosureButton, DisclosurePanel, Menu, MenuButton, MenuItem, MenuItems } from '#headlessui/vue'
import { BellIcon, MenuIcon, XIcon } from '#heroicons/vue/outline'
import HelloWorld from './components/HelloWorld.vue'
</script>
Child:
<template>
<div class="flex flex-col items-center py-16">
<div class="w-96 h-96">
<TransitionRoot
appear
:show="isShowing"
as="template"
enter="transform transition duration-[400ms]"
enter-from="opacity-0 rotate-[-120deg] scale-50"
enter-to="opacity-100 rotate-0 scale-100"
leave="transform duration-200 transition ease-in-out"
leave-from="opacity-100 rotate-0 scale-100 "
leave-to="opacity-0 scale-95 "
>
<div class="w-full h-full bg-gray-400 rounded-md shadow-lg" />
</TransitionRoot>
</div>
</div>
</template>
<script setup>
import { ref, toRefs, watch } from 'vue'
import { TransitionRoot } from '#headlessui/vue'
const props = defineProps({
transition: Function
})
const { transition } = toRefs(props)
const isShowing = ref(true)
watch(transition, () => {
isShowing.value = false
setTimeout(() => {
isShowing.value = true
}, 500)
})
</script>
events should go up and state should go down.
make your child component to watch a property and the button in parent should change the state of that property
update:
const { transition } = toRefs(props)
you might be losing reactivity here.
more info: https://stackoverflow.com/a/64926664/420096
update2:
the way you made it should work, but point directly to the prop is fine too:
https://codesandbox.io/s/relaxed-sea-y95x6c?file=/src/App.vue
Based on Sombriks' feedback, here is the answer:
Parent:
<!-- This example requires Tailwind CSS v2.0+ -->
<template>
<div class="min-h-full">
<Disclosure as="nav" class="bg-gray-800">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex items-center justify-between h-16">
<div class="flex items-center">
<div class="hidden md:block">
<div class="ml-10 flex items-baseline space-x-4">
<button type="button" #click="transition" class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800">Click to transition</button>
</div>
</div>
</div>
</div>
</div>
</Disclosure>
<main>
<div class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
<div class="px-4 py-6 sm:px-0">
<HelloWorld :show="show" />
</div>
</div>
</main>
</div>
</template>
<script setup>
import { Disclosure, DisclosureButton, DisclosurePanel, Menu, MenuButton, MenuItem, MenuItems } from '#headlessui/vue'
import { BellIcon, MenuIcon, XIcon } from '#heroicons/vue/outline'
import { ref } from 'vue'
import HelloWorld from './components/HelloWorld.vue'
const show = ref(true)
const transition = () => {
show.value = !show.value
}
</script>
Child:
<template>
<div class="flex flex-col items-center py-16">
<div class="w-96 h-96">
<TransitionRoot
appear
:show="isShowing"
as="template"
enter="transform transition duration-[400ms]"
enter-from="opacity-0 rotate-[-120deg] scale-50"
enter-to="opacity-100 rotate-0 scale-100"
leave="transform duration-200 transition ease-in-out"
leave-from="opacity-100 rotate-0 scale-100 "
leave-to="opacity-0 scale-95 "
>
<div class="w-full h-full bg-gray-400 rounded-md shadow-lg" />
</TransitionRoot>
</div>
</div>
</template>
<script setup>
import { ref, toRefs, watch } from 'vue'
import { TransitionRoot } from '#headlessui/vue'
const props = defineProps({
show: Boolean
})
const { show } = toRefs(props)
const isShowing = ref(true)
watch(show, () => {
isShowing.value = false
setTimeout(() => {
isShowing.value = true
}, 500)
})
</script>

Method "getChampionName" has type "undefined" in the component definition. Did you reference the function correctly?

I'm trying to use this function (src/api/)
function getChampionName(champId) {
axios.get('http://ddragon.leagueoflegends.com/cdn/12.5.1/data/en_US/champion.json')
.then(({ data }) => {
let list = data
let championList = list.data
for (var i in championList) {
if (championList[i].key == champId) {
return championList[i].id
}
}
})
.catch((err) => console.log(err))
}
export {getChampionName}
In this component (src/components/)
<template>
<div class="w-72">
<header class="rounded-tl-lg rounded-tr-lg bg-slate-400 p-0.5">
<p>Champion's Mastery</p>
</header>
<ul class="grid gap-1 rounded-bl-lg rounded-br-lg bg-slate-50 p-0.5">
<li v-for="champ in masteryData.slice(0,10)" :key="champ.championId">
<div class="flex items-center justify-between">
<div class="flex items-center gap-2">
<img src="https://ddragon.leagueoflegends.com/cdn/12.5.1/img/champion/Karma.png" alt="" class="rounded-lg h-14 w-14">
<div>
<p class="font-medium text-center">{{ getChampionName(champ.championId) }}</p>
<p>Level {{ champ.championLevel }}</p>
</div>
</div>
<p class="text-2xl font-medium">{{ champ.championPoints }} Pts</p>
</div>
</li>
</ul>
</div>
</template>
<script>
import getChampionName from '#/api/search'
export default{
name: 'MasteryInfo',
props: [
'masteryData'
],
methods: {
getChampionName
}
}
</script>
But I'm getting this error Method "getChampionName" has type "undefined" in the component definition. and don't know what does it mean.
It seems you didn't import the method properly.
Change the import into:
import { getChampionName } from '#/api/search';
You can read more about import export in javascript here:
https://javascript.info/import-export
If you think you almost have the same question as this question, you can also refer to this:
Method "showDate" has type "undefined" in the component definition

#click within v-for triggers all #click events

When a single #click is triggered from within the v-for the display property in all of the objects within the array is updated, rather than just by index. I only want that element that is click to receive the event and update the display property, not all of them.
<script>
import TransitionExpand from '#/transitions/transition-expand'
import ResourceCard from '#/components/resource-card'
export default {
components: {
TransitionExpand,
ResourceCard
},
data () {
return {
}
},
methods: {
toggle (evt, i) {
this.status[i].display = !this.status[i].display
}
},
async asyncData ({ app }) {
const { data } = await app.$axios.get('training_modules')
const status = Array(data.trainingModules.length).fill({ display: false })
return {
modules: data.trainingModules,
status
}
}
}
</script>
<template>
<div>
<div class="container px-4 mx-auto mt-16 lg:mt-32">
<div class="flex flex-wrap mb-20">
<h1 class="w-full lg:w-1/2 mb-6">Training Modules</h1>
<p class="w-full lg:w-1/2 leading-7 text-abbey"></p>
</div>
<div
v-for="(item, i) in modules"
:key="item.id"
class="mb-12"
>
<div class="flex items-center">
<h2>{{ item.title }}</h2>
<img #click="toggle($event, i)" class="ml-auto cursor-pointer" src="#/assets/images/icons/plus.svg" alt="open">
</div>
<TransitionExpand v-show="status[i].display">
<div class="">
<p class="mt-6 mb-12">{{ item.description }}</p>
<div class="flex flex-wrap -m-3">
<ResourceCard
v-for="resource in item.resources"
:key="resource.id"
:resource="resource"
/>
</div>
</div>
</TransitionExpand>
</div>
</div>
<BaseFooter />
</div>
</template>
Problem is in const status = Array(data.trainingModules.length).fill({ display: false }) code which is filing all array items with the same object which is observable hence change in display property will be applied to all elements in the array as status[0] === status[1].
Use map instead and it will work as expected:
const status = data.trainingModules.map(() => ({ display: false }));

Remove value from localStorage in Vuejs

friends
Problem
I have the problem that when I am in the video section watching a particular episode, in the local storage the src of the video that I saw before is stored.
My intention is to eliminate the value of the local storage once it leaves the video section.
Template Video
<template>
<!-- Main -->
<main class="flex-1 bg-grey-lightest z-0 py-5 px-0">
<div class="flex flex-wrap max-w-5xl mx-auto">
<!-- main col -->
<div class="w-full md:flex-1">
<!-- player -->
<div class="bg-black relative mb-3">
<video
id="video"
controls
><source :src="videos.video" type="video/mp4"></video>
</div>
<!-- video info -->
<div class="flex flex-wrap items-end">
<!-- title -->
<div class="pb-2">
<h1 class="text-xl my-2">
<div class="p-2 bg-indigo-800 items-center text-indigo-100 leading-none lg:rounded-full flex lg:inline-flex" role="alert">
<span class="flex rounded-full bg-indigo-500 uppercase px-2 py-1 text-xs font-bold mr-3">video</span>
<span class="flex rounded-full bg-indigo-500 uppercase px-2 py-1 text-xs font-bold mr-3">{{content}}</span>
<span class="flex rounded-full bg-indigo-500 uppercase px-2 py-1 text-xs font-bold mr-3">{{state}}</span>
<span class="flex rounded-full bg-indigo-500 uppercase px-2 py-1 text-xs font-bold mr-3">eps - {{eps}}</span>
<span class="font-semibold mr-2 text-left flex-auto">{{Title}}</span>
<svg class="fill-current opacity-75 h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path d="M12.95 10.707l.707-.707L8 4.343 6.586 5.757 10.828 10l-4.242 4.243L8 15.657l4.95-4.95z"/></svg>
</div>
</h1>
<span class="text-base text-grey-darken">{{synopsis}}</span>
</div>
<!-- buttons actions -->
<div class="ml-auto">
<!-- likes -->
<div class="flex relative pb-2">
<!-- like -->
<div class="flex items-center">
<span class="text-black opacity-50 text-sm"> ライウアニミー</span>
</div>
<!-- hate -->
<div class="flex items-center ml-5">
<span class="text-xs text-grey-darken ml-1">🥇</span>
</div>
<div class="absolute w-full h-1 bg-grey pin-b t-5 rounded-full overflow-hidden">
<div class="absolute pin-l pin-t w-3/4 h-full bg-grey-darkest"></div>
</div>
</div>
</div>
<hr class="w-full border-t m-0 mb-3 "/>
</div>
</div>
</div>
</main>
</template>
Script
What I have implemented In the mounted property is that if the video exists, it eliminated the obj videos that belongs to the key vuex.
But what I have done does not do anything, when I leave the video section the video object maintains the src of the video.
<script>
import swal from 'sweetalert';
import {mapState} from 'vuex'
import store from '../store/store'
export default{
name: 'Video',
props: ['Id' , 'Title' , 'Eps' , 'Synopsis' , 'ContentType' , 'State'],
data(){
return{
id: this.Id,
eps: this.Eps,
synopsis: this.Synopsis,
content: this.ContentType,
state: this.State,
}
},
computed:{
...mapState(['videos' , 'isLoading'])
},
watch:{
"Eps": function(value){
this.eps = value;
let eps = this.eps;
let info = {id: this.id , eps: eps}
store.dispatch('GET_ANIME_VIDEO' , info)
swal("Message!", "Wait a few seconds for the video to load\nIt's normal that it takes a bit", "success");
},
"videos.video": function(value){
this.videos.video = value;
document.getElementById('video').load();
}
},
mounted(){
if(this.videos.video){
const vuex = JSON.parse(localStorage.getItem('vuex'));
delete vuex.videos;
localStorage.setItem("vuex", JSON.stringify(vuex));
}
},
};
</script>
Mutation
I think what I have to do is create a mutation to clean the localstorage
export const mutations = {
initialiseStore(state) {
// Check if the ID exists
if(localStorage.getItem('store')) {
// Replace the state object with the stored item
this.replaceState(
Object.assign(state, JSON.parse(localStorage.getItem('store')))
);
}
},
SET_LATEST_DATA(state , payload){
state.latest = payload;
},
SET_VIDEO_ANIME(state , payload){
state.videos = payload;
},
SET_ANIME_ALPHA(state , payload){
state.animesByAlpha = payload;
},
SET_ANIME_GENDER(state , payload){
state.animesByGender = payload;
},
SET_ANIME_SEARCH(state , payload){
state.searchAnimeList = payload;
},
SET_GET_SCHEDULE(state , payload){
state.schedule = payload;
},
SET_MOVIES(state , payload){
state.movies = payload;
},
SET_OVAS(state , payload){
state.ovas = payload;
},
IS_LOADING(state , payload){
state.isLoading = payload;
}
};
Action
GET_ANIME_VIDEO({commit} , info){
console.log("id: " , info.id , "chapter: " , info.eps)
A.get(`${API_URL_ENDPOINT.video}` + "/" + `${info.id}` + "/" + `${info.eps}`)
.then((res) =>{
console.log("video src = " , res.data)
commit('SET_VIDEO_ANIME' , res.data);
commit('IS_LOADING' , false);
}).catch((err) =>{
console.error(err);
});
},
Solution
For something like this, I'd use the Vue lifecycle hook beforeDestroy:
Called right before a Vue instance is destroyed. At this stage the instance is still fully functional.
Example:
export default {
// ... vue component stuff ...
beforeDestroy () {
localStorage.removeItem('vuex');
}
}
Explanation
This will ensure that before the instance is removed from the virtual AND real DOM, we are removing an item from the localStorage called vuex.
Please note, that this does not clear the state that's stored in Vuex. For that, you'd want to create a mutation and call that mutation in the same way from beforeDestroy().
Hope this helps!
My Solution
I found the solution, but I do not know if it is the most optimal. But he does the cleaning.
beforeDestroy(){
const vuex = JSON.parse(localStorage.getItem('vuex'));
if(vuex.videos){
localStorage.removeItem(vuex.videos);
}
}
Actual Problem
When I leave the video session and I want to go see another video, the screen of the previous video remains
My intention is to keep the screen black and the minutes of the video at zero

Categories

Resources