The following Json is recieved by the Vue Script, from a Php script which encodes an Array of Objects into JSON.
[{"title":"Clean Drinking Water","content":"Some Content","link":"abd.html","img":"<img src="kkk.jpg" />"
},
{"title":"Clean AAAAAter Provided","content":"Lore Lipsum
Test","link":"abc.html","img":"<img src="kkk.jpg" width="320" />"
}
]
How do i access title, content, link and image data from this Json using Vue. My Vue Code is
const url="lkl.php?get=json";
const vm=new Vue({
el:'#app',
data:{
results:[]
},
mounted(){
axios.get(url).then(response=>{
this.results=response.data
})
}
});
I have tried {{ results.title }} {{ results[0].title }} but that doesn't seem to work. I am fairly new to Vue. Any help would be much appreciated.
Related
I am currently testing out Headless Wordpress with Vue. Right now I am trying to accomplish to return page content with all gutenberg blocks(Advanced Custom Fields etc).
For this I am using wp-json/wp/v2/pages api to return all pages.
Problem was that this api didn't return content with gutenberg blocks so I decided to use plugin called "REST API blocks". With this I managed to get gutenberg blocks data inside page content.
Is there a way to return gutenberg data inside content without plugin? I wouldn't want to rely on plugin especially when it's outdated.
My code
<template>
<div>
<div v-for="page in pages" v-bind:key="page.id">
<h2>{{ page.title.rendered }}</h2>
//loop trough all gutenberg blocks inside page
<div v-for="block in page.blocks">
//page content as html.
<div v-html="block.attrs.content"></div>
//acf block data. Get field named title
{{ block.attrs.data?.title }}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
pages: [],
};
},
methods: {
async getData() {
try {
let response = await fetch("http://localhost:8000/wp-json/wp/v2/pages");
this.pages = await response.json();
console.log(response);
} catch (error) {
console.log(error);
}
},
},
created() {
this.getData();
},
};
</script>
My json looks like this https://justpaste.it/b43wy
This may not be the most correct way to implement Headless Wordpress with Vue but I am just doing it for learning puropouses.
Any information about Headless Wordpress is very welcome and I am up for discussion and new knowledge.
I am using Markdown file to generate pages for gatby. In order to control the style of pictures, I use html syntax. However, the page generated by gatsby does not display the html part.
This is my markdown file:
---
......frontmatter......
---
......content......
<table>
<tr>
<td><img src="./images/2018/zotero/ZoteroWebDAV.png"></td>
<td><img src="./images/2018/zotero/ZoteroExts.png" width=100%></td>
</tr>
</table>
......content......
Everything else is rendered normally, however, neither the table nor the pictures in it are displayed. Here is my gatsby-config.js.
{
resolve: `gatsby-transformer-remark`,
options: {
excerpt_separator: `<!-- endexcerpt -->`,
plugins: [
// 'gatsby-remark-relative-images',
{
resolve: `gatsby-remark-images`,
options: {
maxWidth: 1200,
},
},
{
resolve: `gatsby-remark-image-attributes`,
options: {
dataAttributes: true
}
},
],
},
},
What can I do to make the html part in Markdown render normally?
You can use as well the built-in dangerouslySetInnerHtml property or any markdown parser like markdown-to-jsx.
Using the first approach, following Gatsby's guides:
import React from "react"
import { graphql } from "gatsby"
export default function Template({data}) {
const { markdownRemark } = data // data.markdownRemark holds your post data
const { frontmatter, html } = markdownRemark
return (
<div className="blog-post-container">
<div className="blog-post">
<h1>{frontmatter.title}</h1>
<h2>{frontmatter.date}</h2>
<div
className="blog-post-content"
dangerouslySetInnerHTML={{ __html: html }}
/>
</div>
</div>
)
}
export const pageQuery = graphql`
query($id: String!) {
markdownRemark(id: { eq: $id }) {
html
frontmatter {
date(formatString: "MMMM DD, YYYY")
slug
title
}
}
}
`
Because you haven't shared your query I've used the one in the guide but tweak it as you wish. As you can see, everything that is in the end of the frontmatter is html:
<div
className="blog-post-content"
dangerouslySetInnerHTML={{ __html: html }}
/>
Using the second approach, and following the previous query structure, the html should be rendered as:
import Markdown from 'markdown-to-jsx';
import React from 'react';
<Markdown>{html}</Markdown>
If there's any hindrance I'd say that the second approach is better because, as the dangerouslySetInnerHTML name suggests, you are potentially exposing your site to XSS (Cross-Site Scripting), while the second approach sanitizes the implementation.
I'm having trouble iterating over data from a json file in Vue JS. I've got everything set up and have access to the json. What am I missing here:
JSON
{
"test": "example",
"data": [
{
"name": "My Name",
"address": "My Address"
}
]
}
Vue JS html
{{ someData['name'] }}
<ul>
<li v-for="item in someData" v-bind:key="item.id">
{{ item }}
</li>
</ul>
and my script:
created() {
this.$http.get('http://localhost:3000/properties.json').then(response => {
// get body data
this.someData = response.body
}, response => {
// error callback
});
}
The result I'm getting is:
Result
As you can see, in my v-for simply specifying item grabs each of the items here, but I want to be able to do something like {{ item['name'] }} and {{ item['address'] }}
The main problem is in your JSON file. VueJS v-for is iterating over the keys in your JSON file, in this case {{ item }} will be getting name and address. That is the reason of your output.
To solve this...
Format your JSON file as
[{name: 'John', address: 'Jane'}]
Doing this your VueJS v-for will be iterating over JSON array and {{ item }} will get the value { name: 'John', address: 'Jane' } and now you can do {{ item.name }} {{ item.address }}
An example here
EDIT: Update your API request code
created() {
this.$http.get('http://localhost:3000/properties.json').then(response => {
// get body data
this.someData = [response.body]
}, response => {
// error callback
});
}
You can simply do the following:
<template v-for="(item, key) in someData">
<span v-if="key == 'address'">{{item}}</span>
</template>
The crucial point is that the v-for="item in someData" part in the component's view iterates over values of the someData object, namely "John" and "Jane".
Depending on what exactly is your goal, you should either reformat the JSON to be an array of objects (as suggested by #F.bernal), or change the logic of v-for directive.
How do convert object to JSON and output it on html page?
public User:UserInfo=
{
firstName: "O",
lastName: "K",
email: "ol#op.com",
country: "uk",
avatarUrl: null,
receiveNotifications: true
}
I wish you had given us a bit more detail in your question, but I will do my best here so bear with me! Let's say you have an object that looks like this
a.component.ts
public obj = {
name: "Oleg",
question: "convert object to json",
description: "Some cool question about angular and JSON"
}
To present this data, your view would look like this
a.component.html
<h1> {{ obj.name }} </h1>
<h2> {{ obj.question }} </h2>
<p> {{ obj.description }} </p>
Please pay attention to how my class member is set to public, this is important whenever you are going to create an AoT build of the application.
If you are having trouble understanding, my simplified example. Check out this example
I can see that you are coming from the jQuery world, but with angular.js things are getting much simpler, please check this jsFiddle:http://jsfiddle.net/pkozlowski_opensource/ASspB/1/
With angular.js you can attach events much, much simpler:
<input type="button" ng-click="showJson()" value="Object To JSON" />
and then in your controller:
$scope.showJson = function() {
$scope.json = angular.toJson($scope.user);
}
In fact this could be done even easier with angular.js filters, check this jsFiddle: http://jsfiddle.net/pkozlowski_opensource/ASspB/2/ which has:
{{user | json}}
You can try the following:
let jsonStr=JSON.stringify(user).
I want to display related artists on my Backbone View by using Spotifys API. So far so good, I managed to get the API/JSON data loaded, but I cant get it displayed in my Handlebars template yet, I get an empty HTML template and I dont know what I'm doing wrong?!?
Here is my Backbone Collection:
ArtistRelated.Collection = Backbone.Collection.extend({
url: function() {
return 'https://api.spotify.com/v1/artists/1HY2Jd0NmPuamShAr6KMms/related-artists';
},
parse: function(artists){
return artists;
}
});
And my Handlebars HTML:
{{#each this}}
<img src="{{images.url}}" alt="{{name}}">
<div>
<h3>{{name}}</h3>
</div>
{{/each}}
The API I took as an example:
https://api.spotify.com/v1/artists/1HY2Jd0NmPuamShAr6KMms/related-artists
What am I doing wrong?
Ok I solved it myself:
After adding/changing the parse method of the collection into:
parse: function(response){
return response.artists;
}
and the Handlebars template:
{{#each this}}
<img src="{{this.images.[0].url}}" alt="{{this.name}}">
<div>
<h3>{{this.name}}</h3>
</div>
{{/each}}
it now works! :-)