Json Array object access - javascript

I want some help in getting data form json array file is in the link
Html
<div>
<div v-for="data in myJson.id " >{{ data }}</div>
</div>
js
import json from '.././json/data.json'
export default {
components: {
MainLayout,
},
data: function(){
return {
myJson:json
}
},
method:{
getjson:function(){
this.json = JSON.parse(myJson);
}
}
}
i want to access only the data with some specific id and i cannot access it using the syntax i am using
edit
Json file

Apparently, you do not even need JSON.parse. It seems to work without it... Put your JSON file in the same directory as your component and try this:
import data from './data.json'
export default {
created () {
for (const item of data[0]['file']) {
console.log(`
Name: ${item.name}
Type: ${item.type}
Size: ${item.filesize}
Dimensions: ${item.dimension[0].width}x${item.dimension[0].height}
`)
}
}
}
You should see information from your JSON file in your console when the page loads.

<script>
import MainLayout from '../layouts/Main.vue'
import json from '.././json/data.json'
export default {
components: {
MainLayout,
},
data: function(){
return {
myJson: json[0].file
}
},
method:{
}
}
</script>
html
<div v-for="data in myJson">
{{ data.name }}
{{ data.filesize}}
{{ data.dimension[0].width}}x{{data.dimension[0].height}}
</div>
using the above code i utilized and used to implemented according to my needs and it worked

Related

How to use plain javascript variables in vue 3 component?

I have a javascript file with some variables and I want to use them in a vue component like this:
<template>
<div> Hello {{ personData.name }} {{ personData.last }} </div>
<button #click="signOut"> Sign Out </button>
</template>
<script>
import { personData } from '<path>'
export default {
...
methods: {
signOut() {
personData.signed_in = false;
}
}
}
</script>
JS file:
export var personData = {
name: '<name>',
last: '<last>',
signed_in: true,
}
It says personData is undefined but obviously it isn't, and also that it was accessed but not defined on instance. I'm new to Vue so I have no idea what I'm doing wrong. Also its important that they are global and not part of the component
Made nothing appear on the page at all
The problem is, you are importing a variable and just using it inside a Vue instance.
VueJS has to know which are reactive data so that it can update the DOM based on its value.
So, you make the following changes to make it work:
<template>
<div> Hello {{ personData.name }} {{ personData.last }} </div>
<button #click="signOut"> Sign Out </button>
</template>
<script>
import { personData } from './presonalData.js'
export default {
data () {
return {
personData //register as reactive data
}
},
methods: {
signOut() {
personData.signed_in = false;
}
}
}
</script>

VueJS 3 - substr / truncation in template / v-for?

I'm pretty new to VueJS and have an understanding problem i couldn't find any help for.
Its pretty simple: I'm getting a JSON through an API with axios. This item contains a description that I want to output on the page.
My code looks something like this:
<template>
<div v-for="item in listitems" :key="item.id">
{{ item.description }}
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import axios from 'axios'
export default defineComponent({
name: 'AllCoupons',
components: {
},
data: function() {
return {
listitems :[]
}
},
mounted: function() {
axios.get('https://api.com/endpoint',
{
headers: {
'Accept': 'application/json'
}
}).then((response) => {
console.log(response);
this.listitems = response.data.data
}).catch(error => {
console.log("ERRR:: ", error.response.data)
});
}
});
</script>
It works fine so far. The problem is that the item.description has too many characters, which I'd like to limit with something like substr. What is the right / best way to do something like this in vue?
I thought about adding a custom function in methods which will be run after the api fetched the data to iterate trough the data and make the modifications then, before passing it back to this.listitems. - But is there a way to do something like this in the template: ?
{{ item.description.substring(1, 4); }}
I knew something like this was possible with Vue 2 and filters if I'm right... But how can I do something like this in Vue 3?
Thanks a lot!!
As suggested in migration guide, you could use a computed property like :
data: function() {
return {
listitems :[]
}
},
computed:{
customItems(){
return this.listitems.map(item=>{
return {...item, description:item.description.substring(1, 4)}
}
}
}
then render that computed property :
<div v-for="item in customItems" :key="item.id">
{{ item.description }}
</div>

Vuejs call other component's method with parameter

I have two components, the first one is for uploading a file and the second one to Show a file. Inside my Upload Component I would like to call the Preview Component and add a Parameter so that a method inside the Preview Component uses a value which is created inside the Upload Component.
So far I have done this:
UploadComponent.vue
<template>
…
<button #click="upload"></button>
<preview-component :url="this.location"></preview-component>
</template >
<script>
import PreviewComponent from '#/js/components/PreviewComponent';
export default {
components: {
'preview-component': PreviewComponent
},
props: ['url'],
data () {
return {
// ...
location: ''
}
},
methods: {
upload() {
// ... upload stuff then update the global var location
this.location = response.data.location;
},
}
}
</script>
This is my Preview Component:
<template>
<div id="body">
///...
</div>
</template>
<script>
export default {
props: ['url'],
methods: {
loadPdf (url) {
//
},
}
}
</script>
So far I am getting the error that url is not defined, so it actually does not sent the url from the UploadCOmponent to the PreviewComponent, how do I manage to sent it?
You got a ninja this in your UploadComponent's template.
It should be <preview-component :url="location"></preview-component>

VUE.JS after parsing trough the JSON getting wrong output

I did [GET] method using Axios. Everything is working fine, when I want to output i get this kind of thing:
http://prntscr.com/mpey70
This is my JS with HTML and VUE code on how I am trying to output it:
HTML, VUE:
<div class="col-lg-6">
<p>Casuals</p>
<ul>
<div v-bind:key="realsub.id+1" v-for="realsub in subnavreal">
<div v-if="nav.linkTitle == 'Male'">
<li><router-link :to="{ path: whiteSpace(realsub.male.casual) }">{{JSON.realsub.male.casual}}</router-link></li>
</div>
<div v-if="nav.linkTitle == 'Female'"></div>
<li><router-link :to="{ path: whiteSpace(realsub.female.casual) }">{{realsub.female.casual}}</router-link></li>
</div>
</ul>
</div>
And this is Related JS code:
import axios from 'axios';
import uuid from 'uuid';
export default {
name: 'navigation',
data(){
return{
subnavreal: []
}
},
props: ["navigation"],
methods:{
whiteSpace(a){
console.log(a);
}
},
async created(){
axios.get('/products.json')
.then(res => this.subnavreal = res.data)
.catch(err => console.log(err));
}
}
</script>
What I want to display is only the name of that object, for example: "Hoodies"
Any solutions? :)
I think you are printing the entire Response. You can use the Object.keys() to print the keys.
let user = {
name: "tom",
age: 20
}
If you want to print the keys [name, age] use Object.keys(user)

VueJS method not returning response from Axios

Trying to figure this out for awhile now and I know it is something simple but can not seem to figure out the issue. My output is {} when I am trying to return a Axios response. When I do not return the entire axios.post my output is nothing. But when I console.log the data it shows up fine in the console. So I know I am getting the data correctly. Below is my test code. Not sure what I am doing wrong, if anyone has a idea it would be greatly appreciated.
<template>
<div>
{{ fetch_name('my_name') }}
</div>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
}
},
methods: {
fetch_name(name) {
return axios.post('example.com/api/names', {custom: 'SELECT name FROM `names` WHERE name = "'+name+'"'}).then(response => {
console.log(response.data[0].name)
return response.data[0].name
})
}
}
}
</script>
Solution for your case:
<template>
<div>
{{ fetch_name('my_name') && result }}
</div>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
result: 'Loading...',
}
},
methods: {
fetch_name(name) {
return axios.post('example.com/api/names', {custom: 'SELECT name FROM `names` WHERE name = "'+name+'"'}).then(response => {
console.log(response.data[0].name)
this.result = response.data[0].name;
return response.data[0].name
})
}
}
}
</script>
But I think better modify logic something like this:
Solution for with control name in UI:
<template>
<div>
<input v-model="name">
{{ result }}
</div>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
name: null,
result: 'Wait for typing',
}
},
watch: {
name(name) {
this.result = 'Loading...';
axios.post('example.com/api/names', {custom: 'SELECT name FROM `names` WHERE name = "'+name+'"'})
.then(response => {
this.result = response.data[0].name;
return response.data[0].name
})
}
},
}
</script>
return response.data[0].name
isn't returning from fetch_name fetch name returns as soon as it does the post....
what you need to do is put the response into your data, then bind to your data, not the method. When the response to post comes in, it will then trigger the UI update.
Also, sending SQL from the client side seems super dangerous.

Categories