In my application I'm working with comment, each product has its own comment.Comment in MySql contains column 'computer_comment' with foreign key(id).When I send 'computer_comment' from axios to laravel comments doesn't shown, I guess that 'computer_comment' is null or undefined.
I tried to send 1 or 2 instead 'computer_comment', in this case it works.
CommentComponent.vue
<template>
<div>
<div v-for="l in list">
<div v-if="l.computer_comment==current">
<div class="card" >
<div class="card body" >
<h4 style="text-decoration: underline">{{l.name}}</h4>
<p >{{l.body}}</p>
</div>
</div>
<br>
</div>
</div>
</div>
</template>
<script>
export default{
props: ['message'],
data(){
return{
list: [],
comment:{
id: '',
user_comment: '',
computer_comment: '',
name: '',
body: ''
},
current: this.message
}
},
created() {
this.show_comment();
},
methods: {
show_comment(){
axios.get('/current_comment').then(result => {
this.list = result.data;
console.log(result.data);
});
},
removeCom(id){
axios.post('/remove/'+id).then(result => {
this.show_comment();
}).catch(err => {
console.log(err);
});
}
},
}
</script>
info.blade.php
<div id="info">
<comment message="{{$computer->id}}"></comment>
.....
</div>
Related
Im building a simple app to practise Nuxt and axios with the CocktailDB API https://www.thecocktaildb.com/api.php. I have troubble getting the images to show rather than just the links. In console.log the links also shows. How do I get the images from the API to show in the list, and not only the link? Thanks in advance!
<template>
<div>
<div>
<SearchDrink/>
</div>
<div>
<div v-for="drink in drinks" :key="drink.id">
<div class="drink">
<p> {{ drink.strDrink
}} </p>
<img src="" alt=""/> {{ drink.strDrinkThumb
}}
<p>Instructions:</p>
<p> {{ drink.strInstructions }} </p>
<div class="ing"> Ingridients:
<p> {{ drink.strIngredient1 }} </p>
<p> {{ drink.strIngredient2 }} </p>
<p> {{ drink.strIngredient3 }} </p>
<p> {{ drink.strIngredient4 }} </p>
<p> {{ drink.strIngredient5 }} </p>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import SearchDrink from '../../components/SearchDrink.vue'
import axios from 'axios'
export default {
components:{
SearchDrink,
},
data(){
return {
drinks: [],
}
},
methods: {
getAllDrinks(){
axios.get('https://thecocktaildb.com/api/json/v1/1/search.php?s=')
.then((response) => {
this.drinks = response.data.drinks
const myDrink = response.data.drinks
console.log(myDrink)
console.log(myDrink.strDrinkThumb)
})
.catch((error) =>{
console.log(error)
})
},
},
created(){
this.getAllDrinks()
},
// methods: {
// searchDrink(){
// if(!this.search){
// return this.drinks
// }else{
// return this.drinks.filter(drink =>
// drink.text.toLowerCase().includes(this.search.
// toLowerCase()))
// }
// }
// },
head(){
return {
title: 'Drinks App',
meta: [
{
hid: 'description',
name: 'description',
content: 'Best place to search a Drink'
}
]
}
}
}
</script>
you're not putting the image inside the src tag.
This can be done using the v-bind directive as
v-bind:src="..." or :src=".."
Example :
new Vue({
el: "#app",
data: () => ({
drinks: []
}),
mounted(){
axios.get('https://thecocktaildb.com/api/json/v1/1/search.php?s=')
.then((response) => {
this.drinks = response.data.drinks
})
}
})
img {
height: 200px;
width: 200px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.2.1/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<ul>
<li v-for="drink of drinks">
<img :src="drink.strDrinkThumb"/>
</li>
</ul>
</div>
I am trying to retrieve data from REST API. I got below code from a tutorial which are not working in my machine but working in that video.
<template>
<div>
<h2>Articles</h2>
<div class="card mb-2" v-for="article in articles" v-bind:key="article.id">
<div class="card-header">
{{ article.title }}
</div>
<div class="card-body">
{{ article.body }}
</div>
</div>
</div>
</template>
<script>
export default {
data(){
return {
articles : [],
article : {
id : '',
title : '',
body : ''
},
article_id : '',
pagination : {},
edit : false
}
},
created(){
this.fetchArticles();
},
methods:{
fetchArticles(){
fetch('api/articles')
.then(res => res.json())
.then(res => {
this.arcticles = res.data;
console.log(res.data);
})
}
}
}
</script>
After few research I changed my code to
<template>
<div>
<h2>Articles</h2>
<div class="card mb-2" v-for="article in articles" v-bind:key="article.id">
<div class="card-header">
{{ article.title }}
</div>
<div class="card-body">
{{ article.body }}
</div>
</div>
</div>
</template>
<script>
export default {
data(){
return {
articles : [],
article : {
id : '',
title : '',
body : ''
},
article_id : '',
pagination : {},
edit : false
}
},
created(){
axios
.get('api/articles')
.then(res => {
this.articles = res.data.data;
console.log(res.data.data);
})
},
}
</script>
and it's working fine.
I want to fix the previous code (from the tutorial). Otherwise I'll not get further lessons.
From MDN documentation, the json() method is implemented on Response body, and it returns a promise wich resolves to result of parsing the body text as json.
response.json().then(data => {
// do something with your data
});
So, when using in fetch, the correct syntax is:
fetchArticles(){
fetch('api/articles')
.then(res => res.json())
.then(data=> {
this.arcticles = data; // the result here contains only the json data, it is not a response object, so it does not have a 'data' property.
console.log(data);
})
}
I'm working on an application to manage some Cvs.
All my resource functions work perfectly (creating and editing new Cvs etc.)
But in my Vue.js part, it's about showing details for every Cv in a show view using Axios to get data from the database or post using a form.
My console shows a reactivity problem about my variables: infos and info.
Here is my show.blade.php code:
#extends('layouts.app')
#section('content')
<div class ="container" id="app">
<div class="container" id="app">
<div class ="row">
<div class="col-md-12">
<div class="panel-panel-primary">
<div class="panel-heading">
<div class="row">
<div class="col-md-18"> <h3 class="panel-title"> Experience </h3></div>
<div class="col-md-2 text-right">
<button class="btn btn-success" > Ajouter</button>
</div>
</div>
</div>
<div class="panel-body" >
<ul class="list-group">
<li class="list-group-item" v-for="info in infos">
<div class="pull-right">
<button class="btn btn-warning btn-sm">Edit</button>
</div>
<h3>#{{ info.titre }}</h3>
<p>#{{ info.body }}</p>
</li>
</ul>
</div>
</div>
</div>
</div>
<div >
<form class="flex flex-col" #submit.prevent="addExperience">
<textarea class="border rounded p-2 mp-3" v-model="info.titre"></textarea>
<textarea class="border rounded p-2 mp-3" v-model="info.body"></textarea>
<button type="submit" class="border rounded py-2">Commenter</button>
</form>
</div>
</div>
</div>
#endsection
#section('javascripts')
<script src="{{ asset('js/vue.js')}}"> </script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
window.Laravel={!! json_encode([
'csrfToken' => csrf_token(),
'idExperience' => $id,
'url' =>url('/')]) !!} ;
</script>
<script>
var app= new Vue({
el:'#app',
data:{
message: '',
infos: [],
info:{
id:0,
cv_id:window.Laravel.idExperience,
titre:'',
body:'',
}},
methods:{
getExperiences: function() {
axios.get(window.Laravel.url+'/getexperiences/'+window.Laravel.idExperience)
.then(response=>{
console.log(reponse.data);
this.info=reponse.data;})
.catch(error =>{
console.log('errors: ', error);})},
addExperience:function(){
axios.post(window.Laravel.url+'/addexperience', this.info)
.then(repsonse => {
if(response.data.etat){
this.infos.unshift(this.info);
this.info={
id:0,
cv_id:window.Laravel.idExperience,
titre:'',
body:'',
};}})
.catch(error =>{
console.log('errors: ', error)})},
created:function(){
this.getExperiences();})};
</script>
#endsection
And my two functions get Experiences and addExperience in CvController:
public function getExperiences($id){
$cv= Cv::find($id);
return $cv->infos;
}
public function addExperience(Request $request){
$info = new Info;
$info->titre=$request->titre;
$info->body=$request->body;
$info->cv_id=$request->cv_id;
$info->save();
return response()->json(['etat'=> true, 'id'=> $info->id]);
}
And these are my routes:
Route::resource('cvs','CvController');
Route::get('/getexperiences/{id}', 'CvController#getExperiences');
Route::post('/addexperience', 'CvController#addExperience');
My console:
There are some syntax errors that need to be fixed first.
There's an extra ")" at the end of your created method
The methods property is missing a closing "}"
There's a missing ")" at the very end to match the opening new Vue( parenthesis.
It's helpful to indent your code to make these things easier to spot.
Then, you'll need to update your data to be a function that returns an object. See Vue Docs - Data Must Be a Function
You also have some typos for the "response" variable.
Lastly, in your HTML you have two divs that have id="app".
Your JS should look something like:
var app = new Vue({
el: '#app',
data: {
message: '',
infos: [],
info: {
id: 0,
cv_id: window.Laravel.idExperience,
titre: '',
body: '',
}
},
methods: {
getExperiences: function () {
axios.get(window.Laravel.url + '/getexperiences/' + window.Laravel.idExperience)
.then(response => {
console.log(reponse.data);
this.info = response.data;
})
.catch(error => {
console.log('errors: ', error);
})
},
addExperience: function () {
axios.post(window.Laravel.url + '/addexperience', this.info)
.then(response => {
if (response.data.etat) {
this.infos.unshift(this.info);
this.info = {
id: 0,
cv_id: window.Laravel.idExperience,
titre: '',
body: '',
};
}
})
.catch(error => {
console.log('errors: ', error)
})
},
created: function () {
this.getExperiences();
}
}
});
Let me know if that works for you.
I'm attempting to nest some components - ultimately I would like to have a component which displays Posts, with a PostItem component used to render each post. Inside the PostItem, I want a list of related comments, with CommentItem to render each comment. I have the posts displayed using the PostItem with no errors, but as soon as I add the Comments I get errors. So to simplify, I've pulled the CommentsList component out and I'm just trying to display it on the page, manually loading in all comments - it's an exact copy of PostsList, except with comment replacing post, but it generates an error:
[Vue warn]: Property or method "commment" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
found in
---> <Comment> at resources/assets/js/components/CommentItem.vue
<CommentsList> at resources/assets/js/components/CommentsList.vue
<Root>
CommentsList.vue
<template>
<div class="media-list media-list-divided bg-lighter">
<comment v-for="comment in comments"
:key="comment.id"
:comment="comment">
</comment>
</div>
</template>
<script>
import comment from './CommentItem'
export default {
components: { comment },
data: function() {
return {
comment: {
id: 1,
content: "",
edited: false,
created_at: new Date().toLocaleString(),
user: {
id: 1,
name: '',
}
},
comments: [
{
id: 1,
content: "",
edited: false,
created_at: new Date().toLocaleString(),
user: {
id: 1,
name: '',
}
}
]
};
},
created() {
this.fetchCommentsList();
},
methods: {
fetchCommentsList() {
axios.get('/api/comments').then((res) => {
//alert(JSON.stringify(res.data[0], null, 4));
this.comments = res.data;
});
},
createComment() {
axios.post('api/comments', {content: this.comment.content, user_id: Laravel.userId, vessel_id: Laravel.vesselId })
.then((res) => {
this.comment.content = '';
// this.comment.user_id = Laravel.userId;
// this.task.statuscolor = '#ff0000';
this.edit = false;
this.fetchCommentsList();
})
.catch((err) => console.error(err));
},
deleteComment(id) {
axios.delete('api/comments' + id)
.then((res) => {
this.fetchCommentsList()
})
.catch((err) => console.error(err));
},
}
}
</script>
CommentItem.vue
<template>
<div>
<a class="avatar" href="#">
<img class="avatar avatar-lg" v-bind:src="'/images/user' + comment.user.id + '-160x160.jpg'" alt="...">
</a>
<div class="media-body">
<p>
<strong>{{ commment.user.name }}</strong>
</p>
<p>{{ comment.content }}</p>
</div>
</div>
</template>
<script>
export default {
name: 'comment',
props: {
comment: {
required: true,
type: Object,
default: {
content: "",
id: 1,
user: {
name: "",
id: 1
}
}
}
},
data: function() {
return {
}
}
}
</script>
I'm pretty new to Vue - I've read so many tutorials and have been digging through the documentation and can't seem to figure out why its working for me with my PostsList component thats an exact copy. It also seems odd that I need both comment and comments in the data return - something that my working Posts version requires.
I'll drop in my working Posts components:
PostsList.vue
<template>
<div>
<div v-if='posts.length === 0' class="header">There are no posts yet!</div>
<post v-for="post in posts"
:key="post.id"
:post="post">
</post>
<form action="#" #submit.prevent="createPost()" class="publisher bt-1 border-fade bg-white">
<div class="input-group">
<input v-model="post.content" type="text" name="content" class="form-control publisher-input" autofocus>
<span class="input-group-btn">
<button type="submit" class="btn btn-primary">New Post</button>
</span>
</div>
<span class="publisher-btn file-group">
<i class="fa fa-camera file-browser"></i>
<input type="file">
</span>
</form>
</div>
</template>
<script>
// import CommentsManager from './CommentsManager.vue';
import post from './PostItem.vue';
export default {
components: {
post
},
data: function() {
return {
post: {
id: 1,
content: "",
edited: false,
created_at: new Date().toLocaleString(),
user: {
id: 1,
name: '',
}
},
posts: [
{
id: 1,
content: "",
edited: false,
created_at: new Date().toLocaleString(),
user: {
id: 1,
name: '',
}
}
]
};
},
created() {
this.fetchPostsList();
},
methods: {
fetchPostsList() {
axios.get('/api/posts').then((res) => {
//alert(JSON.stringify(res.data[0], null, 4));
this.posts = res.data;
});
},
createPost() {
axios.post('api/posts', {content: this.post.content, user_id: Laravel.userId, vessel_id: Laravel.vesselId })
.then((res) => {
this.post.content = '';
// this.post.user_id = Laravel.userId;
// this.task.statuscolor = '#ff0000';
this.edit = false;
this.fetchPostsList();
})
.catch((err) => console.error(err));
},
deletePost(id) {
axios.delete('api/posts' + id)
.then((res) => {
this.fetchPostsList()
})
.catch((err) => console.error(err));
},
}
}
</script>
PostItem.vue
<template>
<div class="box">
<div class="media bb-1 border-fade">
<img class="avatar avatar-lg" v-bind:src="'/images/user' + post.user.id + '-160x160.jpg'" alt="...">
<div class="media-body">
<p>
<strong>{{ post.user.name }}</strong>
<time class="float-right text-lighter" datetime="2017">24 min ago</time>
</p>
<p><small>Designer</small></p>
</div>
</div>
<div class="box-body bb-1 border-fade">
<p class="lead">{{ post.content }}</p>
<div class="gap-items-4 mt-10">
<a class="text-lighter hover-light" href="#">
<i class="fa fa-thumbs-up mr-1"></i> 0
</a>
<a class="text-lighter hover-light" href="#">
<i class="fa fa-comment mr-1"></i> 0
</a>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'post',
props: {
post: {
required: true,
type: Object,
default: {
content: "",
id: 1,
user: {
name: "",
id: 1
}
}
}
},
data: function() {
return {
}
}
}
</script>
I need help with my code please. I can't figure it out. I'm getting a "TypeError: this.$http is undefined" and it's driving me insane. I trace it to $http, but I have no idea how to fix it. I've just finished my Laravel course, but Vue.js is new to me. Here's is my code:
<template>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-body">
<textarea rows="3" class="form-control" v-model="content"></textarea>
<br>
<button class="btn btn-success pull-right" :disabled="not_working" #click="create_post()">
Create a post
</button>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
mounted() {
},
data() {
return {
content: '',
not_working: true
}
},
methods: {
create_post() {
this.$http.post('/create/post', { content: this.content })
.then((resp) => {
this.content = ''
noty({
type: 'success',
layout: 'bottomLeft',
text: 'Your post has been published !'
})
console.log(resp)
})
}
},
watch: {
content() {
if(this.content.length > 0)
this.not_working = false
else
this.not_working = true
}
}
}
</script>
I think you have a error in submitting the post request.
you need to learn about axios.
Try this example.
axios.post('/create/post', this.content).then((response) => {
// do something
})
npm install axios --save
Add Axios to your Vue.js project, you have to import it:
<script>
import axios from 'axios';
export default {
data() {
return {
posts: [],
errors: []
}
},
created() {
let payload={
content:this.content
}
axios.post('/create/post',payload)
.then(response => {
this.posts = response.data
})
.catch(e => {
this.errors.push(e)
})
}
}
</script>