Trying to load json through Vue Axios - json

I'm trying to include a local JSON file from the static directory called blogs.json which has a load of blogs inside it.
I'm currently loading the blogs via Vue Axios which is a module I'm including in Nuxt JS.
Currently, the blogs are being loaded from the json file perfectly fine, however there is a noticeable few ms delay before the blogs are loaded, I'm trying to figure out a better approach to load the json file and populate the blogs array listed inside data()
This is my current code:
<script>
import PageBanner from '~/components/PageBanner';
export default {
head: {
title: 'Site Title: Blog',
meta: [
{ hid: 'description', name: 'description', content: 'Site description' }
]
},
components: {
PageBanner
},
data () {
return {
blogs: [],
isLoading: true
}
},
created () {
this.axios.get("/articles/blogs.json").then((response) => {
this.blogs = response.data
this.isLoading = false
})
}
}
</script>
This works just fine, but how could I modify this to load the json more quickly?

Just import it, do this and it should work God willing:
<template>
<div>
<!-- There should be no delay -->
{{blogs}}
</div>
<template>
<script>
import PageBanner from '~/components/PageBanner';
import blogsFromJson from '~/articles/blogs.json'; // Or wherever it is found
export default {
head: {
title: 'Site Title: Blog',
meta: [
{ hid: 'description', name: 'description', content: 'Site description' }
]
},
components: {
PageBanner
},
data () {
return {
blogs: blogsFromJson, // Just set it here
isLoading: true
}
},
/* No need for this anymore
created () {
this.axios.get("/articles/blogs.json").then((response) => {
this.blogs = response.data
this.isLoading = false
})
}
*/
}
</script>

Related

next-i18next i18n on array of objects

I have an array of objects called "Options", that I use as a prop to a dropdown/select Material-UI component. I want to use the next-i18next library on the labels. I already implemented with success through all the next app just like the documentation explains. I tried using the {t('key')} and it doesn't allow.
import { useTranslation } from 'next-i18next'
const UsersPage = () => {
const { t } = useTranslation('user');
const Options = [
{ value: 'fullName', label: 'Nome' },
{ value: 'cpf', label: 'CPF' },
{ value: 'id', label: 'PadrĂ£o' },
]
...rest of the component
}
export const getStaticProps = async ({ locale }) => ({
props: {
...await serverSideTranslations(locale, ['user', 'home']),
},
})
export default UsersPage;
The msefer answer is right:
`${t("key")}`
inside JSON or string building in props like
const since = `${t('since')}`;
const until = `${t('until')}`;
...
<ListItemText
primary={value.name}
secondary={since + value.beginDate + until + value.endDate}
/>

Antd customRender return raw html

I need to generate html code in a customRender function of one column.
I cannot use scopedSlots as suggested here, since the html code is part of e generic component, and other components pass their columns array as a parameter.
BaseComponent.vue:
<template>
<a-table
:columns="attrs.columns"
:rowKey="record => record[attrs.recordId]"
:dataSource="filteredTableData"
>
</a-table>
</template>
<script>
export default {
props: {
attrs: {
type: Object,
required: true
}
:
</script>
ContactComponent.vue:
<template>
:
<base-component :attrs="attrs"/>
:
</template>
<script>
import BaseComponent from './BaseComponent';
export default {
components: {
BaseComponent
},
data() {
return {
attrs: {
columns: [
title: 'Type',
dataIndex: 'type',
customRender: (val, record) => {
return '<div class="myClass">' + val + </div>';
},
],
recordId: 'contactId'
}
}
}
:
</script>
The problem:
The following code:
customRender: (val, record) => {
return '<div class="myClass">' + val + '</div>';
},
renders this:
Is there a way to force raw html rendering directly from the customRender function?
You can transform your code:
customRender: (val, record) => {
return '<div class="myClass">' + val + '</div>';
},
In this way (if you have JSX support).
customRender: (data) => {
return <div class="myClass"> {data.text} </div>;
},
If you dont have JSX support, you can return a Vnode. Like specified here: https://vuejs.org/guide/extras/render-function.html#creating-vnodes (I didn't try this way).
Or you can try to add support for JSX: https://vuejs.org/guide/extras/render-function.html#jsx-tsx
(My reply is late but may help others.)
==========
Edit:
Here, another exemple, to show you where this piece of code should be (only work with JSX support):
data: function () {
return {
dataSource: [],
columns: [
{
title: 'Website',
dataIndex: "cat_website",
key: "cat_website",
customRender: (data) => {
return <a href={'http://' + data.text} target='_blank'>{data.text}</a>;
},
},
// other columns...
],
// ...
}
}

Json data not showing in vuejs

I am making a vue app. I put a .json file in static directory. I am trying to read it in the default HelloWorld.vue file. But it's not showing in the browser. Here is what it shows in the browser:
My json file looks like this:
{
"status": "success",
"message": "Successfully retrieved all registered applications",
"Applications": [
{
"ApplicationID": "74382DOD",
"ApplicationName": "OIMInstance2",
"ApplicationType": "OIM",
"APIToken": "ZM8R4FRiZWWKbl235u06zbArCdOBPlEKhqHQO8Y9RJ2HgBPC+cZgbIli8fFuNZaey/2tJciJuILIWIn24WTjGA=="
},
{
"ApplicationID": "943ODA6G",
"ApplicationName": "LDAPInstance2",
"ApplicationType": "LDAP",
"APIToken": "R9lDEW5dnN6TZg2sefEEzS6LWMNmFh4iLHMu47LmAsusHl0bZuh2rktSlXqSZRdHHEWq7sP4Xsdy6xNtDYE8xw=="
}
]
}
My code in HelloWorld.vue is:
<template>
<div>
<h1>APPLICATION REGISTRATION</h1>
<div v-for="udata in userData">
Id : {{ udata.ApplicationID }}
</div>
</div>
</template>
<script>
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
export default {
name: 'HelloWorld',
data () {
return {
userData: []
}
},
created: function() {
axios.get('../../static/mockdata.json')
.then(response => {
this.userData = response.data
})
.catch(e => {
//this.errors.push(e)
})
}
}
</script>
Is there anything wrong with my code? How do I show the json data in the browser?
You need to iterate through applications object.Hence in order to get applicationId you will need to set data accordingly by only adding applications data in your userData variable.
Do as below.
this.userData = response.data.Applications

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