2 V-If Statements in the same div? - html

I am attempting to put two conditions into one div, but since I am new to coding, I am not sure where to go from here. Basically what my code is doing is displaying a part table constantly, but I only want to display the table when there are results found. When the no results div displays, I would like the table to not display. If any advice could be spared, it would be greatly appreciated. Here is the code....
<keep-alive>
<PartsTable style="grid-area: contentArea" v-if="displayStore.cardView" />
</keep-alive>
<div id="noResultsDiv" v-if="partStore.filterQuery && !computedList.length">No Results Found</div>
script
<script lang="ts">
import { defineComponent } from "vue";
import { mapStores } from 'pinia'
import PartsTable from "../components/PartsTable.vue";
import ActionButton from "../components/ActionButton.vue";
import PartCardHolder from "../components/PartCardHolder.vue";
import { useDisplayStore } from "../stores/display-store";
import { usePartStore } from "../stores/part-store";
import { PartDefinition } from "../types/PartDefinition";
export default defineComponent({
name: "Home",
components: {
PartsTable,
ActionButton,
PartCardHolder,
},
data() {
return {
pageCount: 50 as number,
emptyStore: false as boolean
}
},
computed: {
...mapStores(useDisplayStore, usePartStore),
computedList(): PartDefinition[] {
return this.partStore.filteredList.slice(0, this.pageCount);
},
},
methods: {
addPart(): void {
this.$router.push({
path: `/add`,
});
},
viewPart(id: PartDefinition["id"]): void {
this.$router.push({
path: `/view/${id}`,
});
},
async updateStorage() {
sessionStorage.setItem("cardView", this.displayStore.cardView.toString())
},
},
async mounted() {
if (sessionStorage.getItem("cardView") == "true") {
this.displayStore.cardView = true
sessionStorage.setItem("cardView", "true")
} else {
this.displayStore.cardView = false
sessionStorage.setItem("cardView", "false")
}
console.log(sessionStorage.getItem("cardView"))
},
unmounted() {
this.partStore.filterQuery = ""
},
});
</script>

You can use vue.js Conditional Rendering v-if/v-else to achieve.
<div v-if="computedList.length">
// Your parts table will come here.
</div>
<div v-else>
// No results div will display here
</div>
I just gave you a way to achieve the requirement. You can modify the condition as per your need.

Related

how I can fix overlap issue in stackbarchart using vue-chartjs

I'm using latest vue-chartjs package with vue3 to create stackbarchart. I've shown the stackbarchart on my app but it's labels are overlapping. I need to know which property can add in options that can fix my issue.
<template>
<Bar
v-if="chartData != null"
:key="id"
:data="chartData"
:options="chartOptions"
/>
</template>
<script>
import { Bar, getElementAtEvent } from "vue-chartjs";
import ChartJSPluginDatalabels from "chartjs-plugin-datalabels";
import uniqueId from "lodash.uniqueid";
import { drilldown } from "#/views/Reports/js/drilldown";
import {
Chart as ChartJS,
Title,
Tooltip,
Legend,
BarElement,
CategoryScale,
LinearScale,
ArcElement
} from "chart.js";
ChartJS.register(
CategoryScale,
LinearScale,
BarElement,
Title,
Tooltip,
Legend,
ArcElement,
ChartJSPluginDatalabels
);
export default {
name: "BarChartStacked",
components: {
Bar,
},
props: ["data", "options", "reportData", "eventInfo", "item", "duringDay"],
data() {
return {
id: null,
};
},
computed:{
chartData() { return this.data; /* mutable chart data */ },
chartOptions() { return this.options; /* mutable chart options */ }
},
mounted() {
this.id = uniqueId();
this.chartOptions.plugins.responsive = true;
if (this.reportData && this.reportData.dataFilter) {
if (this.item.conditions) {
// change cursor to pointer if element is clickable
this.chartOptions.hover = {
onHover: function(e) {
var point =getElementAtEvent(e);
if (point.length) e.target.style.cursor = 'pointer';
else e.target.style.cursor = 'default';
}
}
this.chartOptions.onClick = this.handle;
}
} else {
this.chartOptions.hover = {}
}
},
The stackbarchart should display value for the top most graph only like mention in the picture.

Replace an Url from Json with a button that gives URL to another function

I’m trying to implement a function in my web application, that can discover URLs in a loaded Json via Regular Expressions using angular. Afterwards the URLs get replaced with buttons and when the button gets clicked the exact URL who got replaced gets handed in another function in another component which loads the given URL.
Until now I’m at the point that I can replace the URL of the loaded JSON with a button. I’m using a pipe for that named transform-url.pipe:
import {
Pipe,
PipeTransform,
Input,
Component
} from '#angular/core';
import {
DomSanitizer
} from "#angular/platform-browser";
#Pipe({
name: 'transformUrl',
pure: false
})
export class TransformUrlPipe implements PipeTransform {
constructor(protected sanitizer: DomSanitizer) {}
transform(value: any, ): any {
if (value.match === 0) {
return value;
}
return this.sanitizer.bypassSecurityTrustHtml(
value.replace(/"url:\/\/.*\/.*\/.*"/g, "<button type='button' >Run</button>")
);
}
}
Hmtl:
<h3>Unrecognized JSON data:</h3>
<pre [innerHTML] = "genericJson | transformUrl"></pre>
Sample of Json:
"documentVersion": "1.0",
"documentType": "Urls",
"name": {
"request": {
"version": "1.0",
"abc": [
{
"productUrl": "url://awrtwtgsfgshsfh/sfg/v1/document/jsfhljhl564356lhgljhsljh5895hj",
"attributes": [
{
"attributeSet": {
"attributes": {
"426824828246824828282468248": {
"value": "1"
},
"647474373748648248282824": {
"value": "true"
}
}
}
}
]
},
"productUrl": "url://adgagjfjfjfjhf/sfg/v1/document/adfah5ahfah5jahlkhaliohßjkjlaß73-3",
"attributes": [
{
"attributeSet": {
"attributes": {
"426824828246824828282468248": {
"value": "1"
},
"647474373748648248282824": {
"value": "true"
}
}
}
}
]
},
I found nothing on google on how to do this specific task. Is a pipe even the best solution for this? I tried to implement functions in the pipe but it didnt work.
Another thing that i cant figure out is how i can make every button unique so the application knows which excat URL it should take when the button is clicked? And how can I select the URL and give it in another function in another component?
First of all rather than using pipe, I have created solution in Component only.
Stringify JSON which needs to be get values from. genericJson
Remove first and last ", which is matched in regex.
Using *ngFor, create buttons and pass separate link to click function.
Demo (check console for button click)
EDIT: NEW DEMO.
import { Component } from "#angular/core";
#Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
name = "Angular";
genericJson = { ... some json ... }
formatedOutput: (string | boolean)[] = [];
ngOnInit() {
// adding formatting to make regex search easier
const jsonFormattedString = JSON.stringify(this.genericJson, null, 4);
this.formatedOutput = jsonFormattedString.split('\n');
}
onClick(out: string) {
// do whatever operation on link
const link = out.match(/url:\/\/.*\/.*\/.*/)[0];
console.log(link);
}
urlFound(out: string): boolean {
const match = out.match(/"url:\/\/.*\/.*\/.*"/);
if (match !== undefined && match !== null && match.length > 0) {
return true;
}
return false;
}
}
Use matched links in HTML template,
<div>
<div *ngFor="let out of formatedOutput">
<ng-container *ngIf="urlFound(out); else simple_json"><pre>{{out}}<button (click)="onClick(out)">Link</button></pre></ng-container>
<ng-template #simple_json><pre>{{out}}</pre></ng-template>
</div>
</div>
I think, you should do it like this instead of using pipe:
.html
<button (click)="goTo(genericJson.url)">Run</button>
.ts
genericJson = {
url: "www.google.com"
};
goTo(url: string) {
if (url) {
if (!url.includes("https")) {
url = "https://" + url;
}
window.open(url, "_blank");
}
}

Gatsby image path from json

Edit: Got it working even if it feels kinda wrong this way.. Any ideas to make it possible to only use the filename and not a relative path would be appreciated. Anyway, here is how I got it working:
data.json
[
{
"slug": "bloom",
"name": "Bloom",
"image": {
"src": "../images/socks1.jpg"
}
}
]
Query:
{
allDataJson {
edges {
node {
slug
name
image {
src {
childImageSharp {
fluid {
src
}
}
}
}
}
}
}
}
I am trying to display an image of which the name is stored in data.json and the file itself is in src/images
src/data/data.json
[
{
"slug": "sock1",
"name": "sock1",
"image": "socks1.jpg"
}
]
If instead of the pure filename, I provide a url to any image on the web it works.. Tried getting it to work as follows:
gatsby-config.js
module.exports = {
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
name: `data`,
path: `${__dirname}/src/data`,
},
},
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`,
},
},
`gatsby-transformer-json`,
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
],
}
product.js
import React from 'react'
import { graphql } from 'gatsby'
import Layout from '../components/layout'
import get from 'lodash/get'
class ProductPage extends React.Component {
render() {
const products = get(this, 'props.data.allDataJson.edges')
console.log(products)
return (
<Layout>
{products.map(({ node }) => {
return (
<div key={node.name}>
<p>{node.name}</p>
<img src={node.image} />
</div>
)
})}
</Layout>
)
}
}
export default ProductPage
export const productsQuery = graphql`
query {
allDataJson {
edges {
node {
slug
name
image
}
}
}
}
`
All that's being outputted on the frontend is
<img src="socks1.jpg">
If I query for all files in the GraphiQl I get them, but (not sure about this one) I think the image field is just not recognized as file type field (cant query for src etc)
Any pointers would be much appreciated! :)
Your query should similar to this:
export const productsQuery = graphql`
query {
allDataJson {
edges {
node {
slug
name
image{
publicURL
childImageSharp{
fluid {
...GatsbyImageSharpFluid
}
}
}
}
}
}
}
`
Then you can output the path like this:
<img src={node.image.childImageSharp.fluid.src} />
You don't have to use fluid, you use other types of responsive images

How to let one component correspond with the other for a specific function

I've got a component where I click a color of a machine, when I change colors, the machine gets loaded with a different color inside a image carousel.
Now I also created a component in the bottom with a image gallery of the same machine. How can I make it that the image gallery also changes color when I click the color button in the top of the page?
Important notice: The two components are not in the same parent component but they do load in the same machine images already, so the methods are not wrong I believe.
this is the clickable color button:
<li
v-for="(color, index) in machine.content[0].machine_colors"
:key="color.color_slug"
v-if="color.inStock"
v-on:click="selectColor(index)"
v-bind:class="{ active: (color.color_slug === selectedColor.color_slug)}">
<img v-bind:src="color.color_dash">
</li>
this is the component that changes color:
<div class="product__carousel">
<Carousel showIcon v-if="selectedColor" :machineColor="selectedColor"/> <!-- Image carousel gets loaded in -->
</div>
and the component that needs to change color but does not:
<div id="tab-two-panel" class="panel">
<footerGallery v-if="selectedColor && machine" :machineColor="selectedColor"/>
</div>
Heres the script of the partent component:
export default {
name: 'aboutMachine',
components: {
Collapse,
footerGallery,
},
data() {
return{
selectedColor: this.getMachineColorContent(),
}
},
props: {
main: {
default () {
return {};
},
},
machine: {
default () {
return {};
},
},
},
methods: {
getMachineColorContent() {
if (this.selectedColor) {
return null;
}
return this.machine.content[0].machine_colors[0];
},
selectColor(index) {
this.selectedColor = this.machine.content[0].machine_colors[index];
},
},
}
and the component itself:
export default {
name: 'footerGallery',
props: {
showIcon: Boolean,
machineColor: {
default () {
return {};
},
},
},
data() {
return {
highLightedThumbIndex: 0,
isActive: undefined,
};
},
created() {
this.highLightedThumbIndex = this.highLightedThumbIndex || 0;
},
methods: {
selectThumb(index) {
this.highLightedThumbIndex = index;
},
},
};
This is my main.js
import Vue from 'vue';
import VueYouTubeEmbed from 'vue-youtube-embed'
import FontAwesome from './libs/fa';
import App from './App';
const eventHub = new Vue();
Vue.use(VueYouTubeEmbed);
Vue.component('font-awesome-icon', FontAwesome);
Vue.config.productionTip = false;
/* eslint-disable no-new */
new Vue({
el: '#app',
components: { App },
template: '<App/>',
});
I would use events to accomplish this. The migration guide to Vue2 has a good short explanation of how to do simple event routing without using a full Vuex solution. In your case, you would declare a global event hub in one of your js files:
var eventHub = new Vue();
In your selectColor method you would emit the index selected:
selectColor(index) {
this.selectedColor = this.machine.content[0].machine_colors[index];
eventHub.$emit("select-color",index);
}
And in the footer, you would register a listener for the select-color event that calls selectThumb with the payload of the event (which is the selected index):
created() {
this.highLightedThumbIndex = this.highLightedThumbIndex || 0;
eventHub.$on("select-color",this.selectThumb);
}

Vuejs not passing property to mounted

Have the following code:
export default new Router({
routes: [
{
path: '/noticia/:id',
name: 'Noticia',
component: Noticia,
props: true
}
]
})
export default {
name: 'Noticia',
data () {
return {}
},
props: ['id'],
computed: {
noticia () {
return this.$store.getters.noticia
}
},
mounted: function () {
this.$nextTick(function () {
console.log(id)
// Code that will run only after the
// entire view has been rendered
})
}
}
<div>{{id}}</div>
The problem is {{id}} is showed by html div, but it isn't passed to 'mounted', so, i cannot run my 'console.log(id)' (as it will run a code to bring data and put it into the computed).
I have other code running with the same data, running wheel, cannot understand the error
mounted() {
console.log( this.id )
}
To get it working on mounted, just did:
this.id instead of just id