Vue.js call component method results in an error - javascript

The problem is the following, I basically have one Component which is 'card' and I the cards are rendered inside a Vue called 'dash' using v-for. Now what I try to do is add an on-click event to the card, and I have a method called expand declared inside my Component but I get an error when I try to do so.
My HTML code looks like this
<div id="dash" class="dash" style="margin-left: 350px; margin-top:50px;">
<div v-for="state in states" class="state slide-in-fwd-center" v-bind:style="{'margin-left' : state.margin + 'px'}">
<h3 class="header">{{state.state}}</h3>
<card v-for="card in state.cards" v-bind:overall_progress="card.overall_progress" v-bind:test_progress="card.test_progress" v-bind:status="card.status" v-bind:practice_progress="card.practice_progress" v-bind:due_date="card.due_date" v-bind:study_progress="card.study_progress" v-bind:key="card.id" v-bind:description="card.description"
v-bind:title="card.title" #click="$emit('expand')"></card>
</div>
</div>
The outer div "dash" is a Vue, that has stated and each state holds an array of cards which are Vue Components. The component looks like this
Vue.component("card", {
props: [
"title",
"description",
"due_date",
"study_progress",
"practice_progress",
"test_progress",
"overall_progress",
"status"
],
template: `TEMPLATE CODE HERE`,
methods: {
calcColor: function(value) {
if(value > 89){
return 'bg-success'
}
else if(value < 90 && value > 39){
return 'bg-info'
}
else{
return 'bg-danger'
}
},
expand : function(){
console.log('123')
}
}
});
While the dash is really simple:
var dash = new Vue({
el: "#dash",
data: {
states: []
}
});
I am not sure what might be the problem since the method I am trying to call is defined inside the methods:{} of the Component 'card' itself it is not in the Vue or global function

firstly it might be easier for you to bind just the whole card object and access it on card component. So instead of this:
<div id="dash" class="dash" style="margin-left: 350px; margin-top:50px;">
<div
v-for="state in states"
class="state slide-in-fwd-center"
v-bind:style="{'margin-left' : state.margin + 'px'}"
>
<h3 class="header">{{ state.state }}</h3>
<card
v-for="card in state.cards"
v-bind:overall_progress="card.overall_progress"
v-bind:test_progress="card.test_progress"
v-bind:status="card.status"
v-bind:practice_progress="card.practice_progress"
v-bind:due_date="card.due_date"
v-bind:study_progress="card.study_progress"
v-bind:key="card.id"
v-bind:description="card.description"
v-bind:title="card.title"
#click="$emit('expand')"
></card>
</div>
</div>
you will have that:
<div id="dash" class="dash" style="margin-left: 350px; margin-top:50px;">
<div v-for="state in states" class="state slide-in-fwd-center" v-bind:style="{'margin-left' : state.margin + 'px'}">
<h3 class="header">{{state.state}}</h3>
<card v-for="card in state.cards"
v-bind:card = "card"
#click="$emit('expand')"></card>
</div>
</div>
For the event, don't use the $emit, try just to call expand, like this:
#click="event_name(argument1, argument2)"
so - for your case:
#click="expand"
Be sure, that you define expand method in the component, you are using it.
in this case - in the parent component, not in the card.

Related

Conditionally hide the nth element of a v-for loop without modifying the array. vue 3 composition api search function

I have a ref variable (foxArticles ), which holds a list that contains 100 items. In a v-for loop i loop over each value. As a result, i have 100 values rendered on the page.
<template>
<div class="news_container">
<div
v-for="article in foxArticles"
v-bind:key="article"
class="article_single_cell"
>
<div
class="news_box shadow hover:bg-red-100 "
v-if="containsKeyword(article, keywordInput)"
>
<div class="news_box_right">
<div class="news_headline text-red-500">
<a :href="article.url" target="_blank">
{{ article.title }}
</a>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
const foxArticles = ref([]);
</script>
I also have a search function, which returns the value, if it includes the passed in keyword. The function is used in the child of the v-for loop.
<div class="search_input_container">
<input
type="text"
class="search_input"
v-model="keywordInput"
/>
</div>
<script>
const keywordInput = ref("");
function containsKeyword(article, keywordInput) {
if (article.title.toLowerCase().includes(keywordInput.toLowerCase())) {
return article;
}
}
</script>
The problem is, i can't use .slice() on the foxArticles array in the v-for loop, because that screws up the search functionality, as it returns only the values from the sliced range.
How can i have the access the all of the values of the array, while not rendering all 100 of returned articles on the initial load?
Any suggestions?
I think your approach will make it incredibly complex to achieve. It would be simpler to always iterate over some set, this set is either filtered based on a search-term, or it will be the first 100 items.
I'm not very familiar yet with the Vue 3 composition api so I'll demonstrate with a regular (vue 2) component.
<template>
<div class="news_container">
<div
v-for="article in matchingArticles"
v-bind:key="article"
class="article_single_cell"
>
... news_box ...
</div>
</div>
</template>
<script>
export default {
...
computed: {
matchingArticles() {
var articles = this.foxArticles;
if (this.keywordInput) {
articles = articles.filter(article => {
return this.containsKeyword(article, this.keywordInput)
})
} else {
// we will limit the result to 100
articles = articles.slice(0, 100);
}
// you may want to always limit results to 100
// but i'll leave that up to you.
return articles;
}
},
....
}
</script>
Another benefit is that the template does not need to worry about filtering results.
ok, so i kind of came up with another solution, for which you don't have to change the script part...
instead of having one v-for loop , you can make two of them, where each one is wrapped in a v-if statement div
The first v-if statement says, If the client has not used the search (keywordInput == ''), display articles in the range of (index, index)
The second one says = If the user has written something (keywordInput != ''), return those articles.
<template>
<div class="news_container">
<!-- if no search has been done -->
<div v-if="keywordInput == ''">
<div
v-for="article in foxArticles.slice(0, 4)"
v-bind:key="article"
class="article_single_cell"
>
<div class="news_box shadow hover:bg-red-100 ">
<div class="news_box_right">
<div class="news_headline text-red-500">
<a :href="article.url" target="_blank">
{{ article.title }}
</a>
</div>
</div>
</div>
</div>
</div>
<!-- if searched something -->
<div v-else-if="keywordInput != ''">
<div
v-for="article in foxArticles"
v-bind:key="article"
class="article_single_cell"
>
<div
class="news_box shadow hover:bg-red-100 "
v-if="containsKeyword(article, keywordInput) && keywordInput != ''"
>
<div class="news_box_right">
<div class="news_headline text-red-500">
<a :href="article.url" target="_blank">
{{ article.title }}
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
im not sure how this impacts performance tho, but that's a problem for another day

VueJS: Fixing component order in Bootstrap

I've been having some trouble recently with the order of Vue components in Bootstrap. I'm trying to generate some Bootstrap collapsible content in Vue here's the code so far:
HTML
<div class="col-sm main-content" id="main-content">
<p>
<main-section-button v-for="item in sections"
v-bind:section="item"
v-bind:data-target="'#section-' + item.text"
v-bind:aria-controls="'section-' + item.text">
</main-section-button>
</p>
<main-section v-for="item in sections"
v-bind:id="'section-' + item.text">
</main-section>
</div>
VueJS
Vue.component("main-section-button", {
props: ["section"],
template: String.raw`<button class="btn btn-block btn-dark" type="button" data-toggle="collapse" aria-expanded="false">{{ section.text }}</button>`
});
Vue.component("main-section", {
props: ["section"],
template: String.raw`<div class="collapse"><div class="card card-body"><p>Hello, World!</p></div></div></div>`
});
let app = new Vue({
el: '#main-content',
data: {
sections: [
{ id: 0, text: "example1"},
{ id: 0, text: "example2"}
]
}
});
I have tried to make just one component for main-section and main-section-button, but that did not work because of the requirement to pass an id to the card (collapsible content), and a data-target to the button that collapses and expands the content.
Current Result
Required Result
Is it possible to create a component so that the section content is always below the section button.
Thank you in advance.
I guess you have two options to achieve this:
Create a new component that takes the items and displays both components as you wish.
Do not iterate over the components, instead use a <div> around both components or a non-rendered <template> like this:
<div class="col-sm main-content" id="main-content">
<template v-for="item in sections">
<p>
<main-section-button
v-bind:section="item"
v-bind:data-target="'#section-' + item.text"
v-bind:aria-controls="'section-' + item.text">
</main-section-button>
</p>
<main-section
v-bind:id="'section-' + item.text">
</main-section>
</template>
</div>

Apply an Class by using VueJS condition

I'm trying to apply a class to a <p> tag using a VueJS condition but it doesn't work at all, despite it working on JSfiddle. It's been 3 days now that I'm stuck, please help me.
VueJS (in main.js)
new Vue({
el: "#test",
data: {
selected: "2"
}
});
HTML (App.vue)
<div id="app">
<div id="test">
{{ selected }}
<p :class="{ selection: 1 === selected }">
heyyy 1
</p>
<p :class="{ selection: 2 == selected }">
heyyy 2
</p>
<button #click="selected = 2">Switch</button>
</div>
</div>
I'll assume you're using Vue-CLI since you have a .vue file, but your main.js is using syntax from Vue CDN. Maybe you copied the code from the fiddle instead.
I'll assume too that you have a CSS class named .selection for this to work.
Either way, App.vue has its own component instance which is not the main.js mounting instance (it's one level deeper). Your code creates selected in the mounting root instead of App.vue.
To fix, create it in App.vue <script> section instead:
<template>
<div id="app">
<div id="test">
{{ selected }}
<p :class="{ selection: 1 === selected }">
heyyy 1
</p>
<p :class="{ selection: 2 == selected }">
heyyy 2
</p>
<button #click="selected = 2">Switch</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
selected: "2"
}
}
}
</script>
<style>
.selection {
/* CSS */
}
</style>
to apply class binding in VueJs you can use it as :
:class="{ 'selection(your class name here)': selected === 1}"

In Vue&Vuex, how can I activate onclick method in child component?

I'm trying to edit JS library that already existed but it consisted of Vue. So I studied Vue a little.
The problem is that I made child component called 'Analysis' and want to anchor function. I made tag and bind 'moveAnchor' method to onclick, also declared 'moveAnchor' on methods part. but it didn't work. How can I fix? I'm sorry for being inexperienced.. :(
it is script.js of analysis.
import { mapActions, mapState } from 'vuex';
export default {
name: 'Analysis',
computed: {
checkName : function(){
var flag = this.$store.state.analysis.name;
if(flag.indexOf("/PCs/") != -1){
console.log(flag);
}
}
},
methods: {
moveAnchor: function (id){
var div = document.getElementById(id).scrollIntoView();
}
it is template.html of analysis.
<div :class="$style.scrollarea">
<div :class="$style.dropdown">
<button :class="$style.dropbtn">Analysess</button>
<div :class="$style.dropContent">
<a v-for="item in analyData" v-bind:key="item.id" #onclick="moveAnchor(item.id)">
{{ item.title }}
</a>
</div>
</div>
<span>
{{ checkName }}
</span>
<div v-for="item in analyData">
<h1 v-bind:id="item.id">{{ item.title }}</h1>
<img v-bind:src="item.src" style="width: 100%; height: auto">
</div>
Welcome to StackExchange!
The correct binding for Vue's click event is v-on:click, or #click for shorthand. So when you write #onclick, Vue will never call that.
Just change #onclick to #click and all should work fine.

Vuejs - Accordion

I'm trying to create an accordion using vuejs.
I found some examples online, but what I want is different. For SEO purpose I use "is" and "inline-template", so the accordion is kind of static not fully created in Vuejs.
I have 2 problems/questions:
1) I need to add a class "is-active" on the component based on user interaction(clicks), because of this I receive the following error.
Property or method "contentVisible" is not defined on the instance but
referenced during render. Make sure to declare reactive data
properties in the data option.
This probable because I need to set it at instance level. But "contentVisible" have a value (true or false) different for each component.
So I thought using at instance level an array of "contentVisible" and a props (pass thru instance) and custom events on child to update the instance values.
2) Could work but it is a static array. How can I make a dynamic array (not knowing the number of item components) ?
<div class="accordion">
<div>
<div class="accordion-item" is="item" inline-template :class="{ 'is-active': contentVisible}" >
<div>
<a #click="toggle" class="accordion-title"> Title A1</a>
<div v-show="contentVisible" class="accordion-content">albatros</div>
</div>
</div>
<div class="accordion-item" is="item" inline-template :class="{ 'is-active': contentVisible}" >
<div>
<a #click="toggle" class="accordion-title"> Title A2</a>
<div v-show="contentVisible" class="accordion-content">lorem ipsum</div>
</div>
</div>
</div>
var item = {
data: function() {
return {
contentVisible: true
}
},
methods: {
toggle: function(){
this.contentVisible = !this.contentVisible
}
}
}
new Vue({
el:'.accordion',
components: {
'item': item
}
})
Update
I create the following code but the custom event to send the modification from component to instance is not working, tabsactive is not changing
var item = {
props: ['active'],
data: function() {
return {
contentVisible: false
}
},
methods: {
toggle: function(index){
this.contentVisible = !this.contentVisible;
this.active[index] = this.contentVisible;
**this.$emit('tabisactive', this.active);**
console.log(this.active);
}
}
}
new Vue({
el:'.accordion',
data: {
tabsactive: [false, false]
},
components: {
'item': item
}
})
<div class="accordion" **#tabisactive="tabsactive = $event"**>
<div class="accordion-item" is="item" inline-template :active="tabsactive" :class="{'is-active': tabsactive[0]}">
<div>
<a #click="toggle(0)" class="accordion-title"> Title A1</a>
<div v-show="contentVisible" class="accordion-content">albatros</div>
</div>
</div>
<div class="accordion-item" is="item" inline-template :active="tabsactive" :class="{'is-active': tabsactive[1]}">
<div>
<a #click="toggle(1)" class="accordion-title" > Title A2</a>
<div v-show="contentVisible" class="accordion-content">lorem ipsum</div>
</div>
</div>
</div>
This works for me:
<template>
<div>
<ul>
<li v-for="index in list" :key="index._id">
<button #click="contentVisible === index._id ? contentVisible = false : contentVisible = index._id">{{ index.title }}</button>
<p v-if='contentVisible === index._id'>{{ index.item }}</p>
</li>
</ul>
</div>
</template>
<script>
export default {
name: "sameName",
data() {
return {
contentVisible: false,
list: [
{
_id: id1,
title: title1,
item: item1
},
{
_id: id2,
title: title2,
item: item2
}
]
};
},
};
</script>
On point 1:
You have to define contentVisible as a vue instance variable, as you have accessed it with vue directive v-show, it searches this in vue data, watchers, methods, etc, and if it does not find any reference, it throws this error.
As your accordion element is associated with the parent component, you may have to add contentVisible data there, like following:
new Vue({
el:'.accordion',
data: {
contentVisible: true
}
components: {
'item': item
}
})
If you have multiple items, you may use some other technique to show one of them, like have a data variable visibleItemIndex which can change from 1 to n-1, where n is number of items.
In that case, you will have v-show="visibleItemIndex == currentIndex" in the HTML.
You can as well have hash for saving which index are to de displayed and which to be collapsed.
On point 2:
You can use v-for if you have dynamic arrays. you can see the documentation here.
I'm having a real hard time understanding what exactly it is you want or why you would want it, but I think this does it?
Vue.component('accordion-item', {
template: '#accordion-item',
methods: {
toggle() {
if(this.contentVisible){
return
}
if(this.$parent.activeTab.length >= 2){
this.$parent.activeTab.shift()
}
this.$parent.activeTab.push(this)
}
},
computed: {
contentVisible() {
return this.$parent.activeTab.some(c => c === this)
}
}
})
const Accordion = Vue.extend({
data() {
return {
activeTab: []
}
},
methods: {
handleToggle($event) {
this.activeTab = []
}
}
})
document.querySelectorAll('.accordion').forEach(el => new Accordion().$mount(el))
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<template id="accordion-item">
<div class="accordion-item" :class="{ 'is-active': contentVisible}">
<slot name="title"></slot>
<div v-show="contentVisible" class="accordion-content" #click="$emit('toggle', $event)">
<slot name="content"></slot>
</div>
</div>
</template>
<div class="accordion">
<accordion-item #toggle="handleToggle">
<p slot="title">a title</p>
<p slot="content">there are words here</p>
</accordion-item>
<accordion-item #toggle="handleToggle">
<p slot="title">titles are for clicking</p>
<p slot="content">you can also click on the words</p>
</accordion-item>
<accordion-item #toggle="handleToggle">
<p slot="title">and another</p>
<p slot="content">only two open at a time!</p>
</accordion-item>
<accordion-item #toggle="handleToggle">
<p slot="title">and #4</p>
<p slot="content">amazing</p>
</accordion-item>
</div>

Categories

Resources