I need to get the URL of a picture to show my img :src tag. I tryied:
<img class="card-img-top" :src="noticia.Fotos.Link" alt="Card image cap">
This is my HTML:
<div class="col-lg-4" v-for="noticia in noticias">
<div class="row">
<div class="card mt-3 col-lg-10 offset-lg-1">
<img class="card-img-top" :src="noticia.Fotos.Link" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">{{noticia.Titulo}}</h5>
<p class="card-text text-center">
{{noticia.Descricao}}
</p>
</div>
</div>
</div>
</div>
This is my script:
<script>
new Vue({
el: '#noticia',
data: {
UnidadeId: "",
Identificador: "",
Tipo: "",
},
data() {
return {
noticias: [],
}
},
mounted() {
var self = this
axios.get('URL', {
params: this.axiosParams
})
.then(response => {
console.log(response);
self.noticias = response.data
})
.catch(error => {
console.log(error);
})
},
computed: {
axiosParams() {
const params = new URLSearchParams();
params.append('UnidadeId', '31');
params.append('Identificador', '0');
params.append('Tipo', '1');
return params;
}
},
})
</script>
The response:
[
{
"ItemId": 902,
"Titulo": "Noticia",
"Descricao": "Noticia",
"Data": "/Date(1590593442191)/",
"QtdeCurtidas": 0,
"QtdeComentarios": 0,
"Curtido": false,
"Observacao": null,
"Fotos": [
{
"FotoId": 1508,
"Link": "http://agro.aloapp.com.br/Imagens/cVV4S0dINGRESm9IN3IxM2swYXVjZz09/Item/bg_carousel_2.jpg"
}
],
"Videos": [],
"IsVideo": false
}
]
You're trying to retrieve an element from an array (not an ArrayList) which means you need to specify which element in the array you want. In Javascript, this works by specifying the index of the element in brackets after the array name. If you want the first element, you can do noticia.Fotos[0].Link.
Related
So I have a dropzone file uploader. each successfull upload returns the following
File: {
"upload": {
"uuid": "f89f409b-7e49-4503-98d8-dc060e75b874",
"progress": 0,
"total": 5017004,
"bytesSent": 0,
"filename": "20190902_115950.jpg"
},
"status": "error",
"previewElement": {},
"previewTemplate": {},
"accepted": false,
"dataURL": "data:image/jpeg;base64,/9j/4XGiRXh/WU8GGXVL5BHN5PW...",
"width": 3024,
"height": 4032
}
I have a laravel backend with a request validation for this:
rules = [
...
'featured_image' => 'image',
]
However, my laravel backend returns that the featured image field must be an image. So I'm not sure what format the backend expects.
My dropzone component looks like this:
<template>
<div
class="dropzone mb-3 dz-clickable"
:class="[multiple ? 'dropzone-multiple' : 'dropzone-single']"
>
<div class="fallback">
<div class="custom-file">
<input
type="file"
class="custom-file-input"
id="projectCoverUploads"
:multiple="multiple"
/>
<label class="custom-file-label" for="projectCoverUploads"
>Choose file</label
>
</div>
</div>
<div
class="dz-preview dz-preview-single"
v-if="!multiple"
:class="previewClasses"
ref="previewSingle"
>
<div class="dz-preview-cover">
<img class="dz-preview-img" data-dz-thumbnail />
</div>
</div>
<ul
v-else
class="dz-preview dz-preview-multiple list-group list-group-lg list-group-flush"
:class="previewClasses"
ref="previewMultiple"
>
<li class="list-group-item px-0">
<div class="row align-items-center">
<div class="col-auto">
<div class="avatar">
<img class="avatar-img rounded" data-dz-thumbnail />
</div>
</div>
<div class="col ml--3">
<h4 class="mb-1" data-dz-name>...</h4>
<p class="small text-muted mb-0" data-dz-size>...</p>
</div>
<div class="col-auto">
<button data-dz-remove="true" class="btn btn-danger btn-sm">
<i class="fas fa-trash"></i>
</button>
</div>
</div>
</li>
</ul>
</div>
</template>
<script>
export default {
name: "dropzone-file-upload",
props: {
options: {
type: Object,
default: () => ({}),
},
value: [String, Object, Array],
url: {
type: String,
default: "http://",
},
multiple: Boolean,
previewClasses: [String, Object, Array],
},
model: {
prop: "value",
event: "change",
},
data() {
return {
currentFile: null,
files: [],
showList: false,
};
},
methods: {
async initDropzone() {
let Dropzone = await import("dropzone");
Dropzone = Dropzone.default || Dropzone;
Dropzone.autoDiscover = false;
let preview = this.multiple
? this.$refs.previewMultiple
: this.$refs.previewSingle;
let self = this;
let finalOptions = {
...this.options,
url: this.url,
thumbnailWidth: null,
thumbnailHeight: null,
previewsContainer: preview,
previewTemplate: preview.innerHTML,
maxFiles: !this.multiple ? 1 : null,
acceptedFiles: !this.multiple ? "image/*" : null,
init: function () {
this.on("addedfile", function (file) {
if (!self.multiple && self.currentFile) {
// this.removeFile(this.currentFile);
}
self.currentFile = file;
});
},
};
this.dropzone = new Dropzone(this.$el, finalOptions);
preview.innerHTML = "";
let evtList = [
"drop",
"dragstart",
"dragend",
"dragenter",
"dragover",
"addedfile",
"removedfile",
"thumbnail",
"error",
"processing",
"uploadprogress",
"sending",
"success",
"complete",
"canceled",
"maxfilesreached",
"maxfilesexceeded",
"processingmultiple",
"sendingmultiple",
"successmultiple",
"completemultiple",
"canceledmultiple",
"totaluploadprogress",
"reset",
"queuecomplete",
];
evtList.forEach((evt) => {
this.dropzone.on(evt, (data) => {
this.$emit(evt, data);
if (evt === "addedfile") {
this.files.push(data);
this.$emit("change", this.files);
} else if (evt === "removedfile") {
let index = this.files.findIndex(
(f) => f.upload.uuid === data.upload.uuid
);
if (index !== -1) {
this.files.splice(index, 1);
}
this.$emit("change", this.files);
}
});
});
},
},
async mounted() {
this.initDropzone();
},
};
</script>
<style></style>
I have tried to use file system (fs module) but, not getting that how to use that FS module.
could anyone explain with proper example.
I was doing an example in vue js.
Create component
Added json file
Pass records as props on component
listen that props on another component
and render student list and perform remove record
Now next i want to Pass updated list using emit & update the JSON as well
This code is working properly just i want to update local json file after delete record.
StudentRegistration.vue
<template>
<div class="container">
<div class="row">
<template v-if="students.length">
<!-- {{student.length}} -->
<studentCard class="student__parent" v-for="student in students" :key="student.id" :student="student" #studentRemoveId="studentRemoveId"/>
</template>
<template v-else>
<div class="not__available">
Data not available
</div>
</template>
</div>
</div>
</template>
<script>
import studentCard from './studentCard.vue'
import studentData from '../data/StudentData.json'
export default {
name: 'StudentRegi',
components:{
studentCard
},
data() {
return {
students: studentData,
}
},
methods: {
studentRemoveId(studid){
this.students = this.students.filter( item => {
console.log('hey there ::=> ', item);
return item.id !== studid.id
});
}
},
}
</script>
studentCard.vue
<template>
<div>
<span class="student__remove" #click="removeStudent(student)">X</span>
<div class="student__inner">
<div class="student__image">
<img :src="student.avatar" alt="">
</div>
<div class="student__name student-detail">
<div>Name</div>
<div>{{student.fname}} {{student.lname}}</div>
</div>
<div class="student__age student-detail">
<div>Age</div>
<div>{{student.age}}</div>
</div>
<div class="studet_email student-detail">
<div>Email</div>
<div>{{student.email}}</div>
</div>
<div class="student__phone student-detail">
<div>Phone</div>
<div>{{student.phone}}</div>
</div>
</div>
</div>
</template>
<script>
export default {
name:'StudentCard',
props:['student'],
methods: {
removeStudent(studid){
this.$emit('studentRemoveId', studid);
}
},
}
</script>
data.json
[
{
"id": 1,
"fname": "Atul",
"lname": "Bhavsar",
"age": "10 Years",
"email": "atul#gmail.com",
"phone": "9685958698",
"avatar": "https://i.postimg.cc/d3ykpLs8/stud1.jpg"
},
{
"id": 7,
"fname": "Foram",
"lname": "Dobariya",
"age": "20 Years",
"email": "sanju#gmail.com",
"phone": "9856985698",
"avatar": "https://i.postimg.cc/QtWp5XBn/stud7.jpg"
},
]
Hey After some searches I found a solution so sharing here it may help who stuck related to this issue,
As i show above code i just wanted to add code where i can write my json file. so i have made some changes in code, that is as below.
Add command in CMD :
json-server --watch './src/data/studentData.json' --port 3001
then it will provide local link from where you can open you json data
Resources
http://localhost:3001/studente
see below image :
StudentRegistration.vue
this code should be in script tag in StudentRegistration.vue component
In this file added below code added code in method and created create method
export default {
name: 'StudentRegi',
components:{
studentCard
},
data() {
return {
studentsGetData: []
// studentsGetData: studentData,
}
},
methods: {
studentRemoveId(studid){
fetch(`http://localhost:3001/studente/${studid.id}`,
{
method: 'DELETE',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}).then(resp => {
console.log('res ::=> ', resp.data);
resp.data;
}).catch(error => {
console.log(error);
});
this.studentsGetData = this.studentsGetData.filter( item => {
return item.id !== studid.id
});
}
},
async created(){
await fetch('http://localhost:3001/studente')
.then(res => res.json())
.then(data => {
console.log('data ::=> ', data);
this.studentsGetData = data
} )
.catch(err => console.log(err.message))
}
}
Now Run your project
I am creating a time application using the Openweather API. I try to show the meteorological icon corresponding to the selected city and the meteorological state.
My code is as follows:
HTML:
<div class="column">
<div class="media-content">
<div class="content">
<p>
<strong>
<h1 class="has-text-inf o"> {{ ciutatActual.weather[0].icon }} </h1>
</strong>
</p>
</div>
</div>
</div>
javascript:
var vm = new Vue({
el: '#eltemps',
data: {
selectedCity: "",
ciutatActual: null,
ciutats: [
"Barcelona",
"Lleida",
"Zaragoza",
"Sevilla",
"Madrid",
"Paris",
"Melbourne",
"Moscow",
"Pekin",
"Marrakech"]
},
created: function () {
this.selectedCity = this.ciutats[0]
},
watch: {
selectedCity: function (){
this.getWeather(this.selectedCity)
}
},
methods: {
getWeather(city) {
const url = 'https://api.openweathermap.org/data/2.5/weather?q=' + city + '&units=metric&lang=ca&appid=8660dddfbe5f16ee37dbd6883d8f07d5';
fetch(url)
.then(function (response) {
return response.json()
})
.then(function (item) {
vm.ciutatActual = item;
})
.catch(function(error) {
console.log(error);
})
},
itemClicked: function(item) {
this.getWeather();
this.onClick(item);
}
}
})
The ruling comes from here: {{ciutatactual.weather [0] .icon}}
that instead of showing the icon it shows me just one code
So I'm going to be explaining this in the best way possible as I don't understand what might be causing this issue on my end as I feel like I've followed all of the directions and keep hitting a brick wall.
Here is my vue.js app:
new Vue({
name: 'o365-edit-modal-wrapper',
el: '#o365-modal-edit-wrapper',
data: function() {
const default_apps = [
{
'post_title': 'Excel',
}, {
'post_title': 'Word',
}, {
'post_title': 'SharePoint',
}];
console.log(default_apps);
const default_apps1 = this.get_array_of_post_objects('application_launcher');
console.log(default_apps1);
return {
available_list: [],
selected_list: default_apps.map(function(name, index) {
return {
name: name.post_title,
order: index + 1,
fixed: false
};
}),
}
},
methods: {
get_array_of_post_objects(slug) {
let items = [];
wp.api.loadPromise.done(function () {
const Posts = wp.api.models.Post.extend({
url: wpApiSettings.root + 'menus/v1/locations/' + slug,
});
const all_posts = new Posts();
all_posts.fetch().then((posts) => {
items.push(...posts.items);
});
});
return items;
},
},
computed: {
dragOptions() {
// Pass in additional <draggable> options inside the return for both lists.
return {
tag: 'div',
group: 'o365apps',
disabled: !this.editable,
ghostClass: "ghost",
};
},
},
});
Inside my methods, I have a method called get_array_of_post_objects which returns an array of objects that I'm pulling through.
So inside data, I'm console logging my manual default_apps and my default_apps1 which is the method. Both of the arrays of objects have post_title: "something" inside.
Here is the return that I'm getting:
Inside my mapping, when I define default_apps, my IDE returns some result for name but when I switch it over to default_apps1, it's not finding any results as shown below:
I don't know what else to look at - All help would be appreciated!
Here is the HTML code if that is needed:
<div class="column is-half-desktop is-full-mobile buttons">
<nav class="level is-mobile mb-0">
<div class="level-left">
<div class="level-item is-size-5 has-text-left">Selected</div>
</div>
<div class="level-right">
<div class="level-item" #click="orderList()"><i class="fas fa-sort-alpha-up is-clickable"></i></div>
</div>
</nav>
<hr class="mt-1 mb-3">
<!-- Decorator: # also known as v-on: -->
<!-- Bind: : also known as v-bind: -->
<draggable class="list-group"
v-model="selected_list"
v-bind="dragOptions"
:move="onMove"
#add="onAdd"
#remove="onRemove"
#start="isDragging=true"
#end="isDragging=false">
<button class="button is-fullwidth is-flex list-group-item o365_app_handle level is-mobile" v-for="(app, index) in selected_list" :key="app.order">
<div class="level-left">
<span class="icon" aria-hidden="true">
<img :src="`<?= Path::o365('${app.name}' . '.svg'); ?>'`" />
</span>
<span>{{app.name}}</span>
</div>
<div class="level-right is-hidden-desktop">
<span class="icon has-text-danger is-clickable" #click="remove(index)">
<i class="fas fa-times"></i>
</span>
</div>
</button>
</draggable>
</div>
I'm not 100% sure what your app is supposed to do, so modify it for your needs.
Here the selected_list will be empty first.
Then we call your method, which is asynchronous, and once it's done selected_list gets populated.
new Vue({
name: 'o365-edit-modal-wrapper',
el: '#o365-modal-edit-wrapper',
data: function() {
return {
available_list: [],
selected_list: [],
}
},
created() {
this.get_array_of_post_objects("add-your-slug")
},
methods: {
get_array_of_post_objects(slug) {
wp.api.loadPromise.done(function() {
const Posts = wp.api.models.Post.extend({
url: wpApiSettings.root + 'menus/v1/locations/' + slug,
});
const all_posts = new Posts();
all_posts.fetch().then((posts) => {
// You might want to modify posts for your needs
this.selectedList = posts
});
});
},
},
});
I am creating a simple SPA using vue.js and axioz as a scripts (not cli, etc)
So far I am able to pull data from a json then render and paginate the list,and when an item is clicked I am able to console log the data for the specific entry.
HTML
<!--app-->
<div id="app">
<!--articles-->
<div class="row" style="background: #111; padding: 8em 0; width: 50%;">
<div class="ctr">
<div class="row articles page_content" style="padding: 0;">
<ul>
<li v-for="(post) in displayedPosts" #click="getSingle(post.id)">
<router-link :to="{ path: '/post/'+ post.id}" class="flex" >
<div class="row article_thumb">
<img :src="post.url" :alt="post.title"/>
</div>
<div class="row article_excerpt">
<h3 class="title">{{post.title }}</h3>
</div>
</router-link>
</li>
</ul>
</div>
<div class="row pagination">
<button type="button" v-if="page != 1" #click="page--"> << </button>
<button type="button" v-for="pageNumber in pages.slice(page-1, page+5)" #click="page = pageNumber"> {{pageNumber}} </button>
<button type="button" #click="page++" v-if="page < pages.length"> >> </button>
</div>
</div>
</div>
<!--articles-->
<div class="row" style="background: #000; padding: 8em 0; width: 50%;">
<div class="flex router">
<router-view></router-view>
</div>
</div>
</div>
<!--app-->
VUE.JS
const Home = {
template: "<div><h1>Click an article to update this view</h1></div>"
};
//post
var Post = {
template:
'<div class="row"><h1>Display data for Post ID # {{$route.params.id}} here</h1><p style="color: red;">This is where I am stuck, cant display the post data, see example below.</p><p>{{title}}</p></div>',
//post methods
methods: {
//get single post
getSingle: function(id) {
var self = this;
this.id = this.$route.params.id;
this.title = this.title;
axios
.get(this.baseUrl, {
params: {
id: this.id,
}
})
.then(response => {
this.post = response.data;
this.title = response.data.title;
console.log(this.title);
console.log(this.post);
console.log("You clicked post ID #" + this.id);
})
.catch(response => {
console.log(error);
});
}
},
//post methods
//post data
data() {
return {
baseUrl: "https://jsonplaceholder.typicode.com/photos",
posts: [],
title: this.title
};
},
//post created
created() {
this.getSingle(this.$route.params.id);
},
watch: {
"$route.params": {
handler(newValue) {
const { id } = newValue;
this.getSingle(id);
},
immediate: true
}
}
};
//post
//router
const router = new VueRouter({
routes: [
{ path: "/", component: Home },
{ path: "/post/:id", component: Post }
]
});
//initial state
var paginationApp = new Vue({
el: "#app",
router: router,
data: {
posts: [],
baseUrl: "https://jsonplaceholder.typicode.com/photos",
page: 1,
perPage: 2,
pages: []
},
//initial state methods
methods: {
//get single
getSingle() {},
//get posts
getPosts() {
axios
.get(this.baseUrl)
.then(response => {
this.posts = response.data;
})
.catch(response => {
console.log(response);
});
},
//set pages
setPages() {
let numberOfPages = Math.ceil(this.posts.length / this.perPage);
for (let index = 1; index <= numberOfPages; index++) {
this.pages.push(index);
}
},
//paginate
paginate(posts) {
let page = this.page;
let perPage = this.perPage;
let from = page * perPage - perPage;
let to = page * perPage;
return posts.slice(from, to);
}
},
//created
created() {
this.getPosts();
},
//watch
watch: {
posts() {
this.setPages();
}
},
//computed
computed: {
displayedPosts() {
return this.paginate(this.posts);
}
}
});
//initial state
Or see this codepen for full example https://codepen.io/flashvenom/pen/YozyMx and be sure to checkout the console log.
My problem is i cannot console log the title or any internal fields of the data object, as I want to be able to add the title etc into the view area.
Any help or pointers would be much appreciated.
The response is in array form and you cannot access array object element without looping array.
If you wish to get title of first post, then you can do as shown below,
this.title = response.data[0].title
To access all posts title, you can use v-for loop in you vue template. Here is little example on how you can accomplish that,
<div v-for="post in posts">
<span>{{ post.title }}</span>
</div>