In my blog-like Vue.js app, the posts are rendered in a v-for loop. When a button under each post is clicked, its comments are fetched from the server and attributed like this, as post objects have no comments attribute:
`this.$set(post, 'comments', res.data.comments) ;`
The code to render the comments is this:
<div v-for="(c, j) in post.comments" :key="j">
<span>{{c.body}}</span>
<span v-if="post.user_id==userId" #click="delComment(c, post)">Delete me!</span>
</div>
And the deleteing method:
delComment(c, post) {
const payload = {
token: this.token,
cid: c.id
}
axios.delete(this.BASE_URL + "/api/comment", { data: payload } )
.then( (res)=> {
post.comments = this.post.comments.filter((comment)=>{
return comment.id != c.id
});
this.$set(post, 'comments', post.comments) ;
})
.catch( error => {
console.log(error);
});
},
But when I click the Delete link, I get this error in the console:
TypeError: Cannot read property 'comments' of undefined
at eval (Home.vue?76f2:540)
How can I fix this?
You're missing this before post :
//v-------------//here
this.post.comments = this.post.comments.filter((comment)=>{
return comment.id != c.id
});
and here :
//----------v--------------------v
this.$set(this.post, 'comments', this.post.comments) ;
Update :
i was assuming that you a property called post in your data object as follows:
data(){
return{
post:[]
...
}
}
so in this case you should remove any this before post variable.
Alright, I realized that the culprit was an extra this in this.post.comments.filter((comment).
The working code is this:
delComment(c, post) {
const payload = {
token: this.token,
cid: c.id
}
axios.delete(this.BASE_URL + "/api/comment", { data: payload } )
.then( (res)=> {
post.comments = post.comments.filter((comment)=>{
return comment.id != c.id
});
this.$set(post, 'comments', post.comments) ;
})
.catch( error => {
console.log(error);
});
},
Thanks guys for sharing your thoughts!
Related
but i can't show the comments with v-for and i don't understand why my comment data is not working.
I know there is an error but I can't find it.
My request returns a data , but i can't display it my loop.
Thanks for your help
In store/index.js
state :{
dataComments:[]
}
mutation: {
getComments(state, dataComments) {
console.log(dataComments)
state.dataComments = dataComments;
},
}
action: {
getArticleComments: ({ commit }, dataArticles) => {
return new Promise(() => {
instance.get(`/comment/${dataArticles.article_id}`)
.then(function () {
commit('getComments');
})
.catch(function (error) {
console.log(error)
})
})
},
}
in my views/home.vue
export default {
name: "Home",
data: function () {
return {
articles: [],
comments: [],
}
},
methods: {
getArticleComments(comment) {
this.$store
.dispatch("getArticleComments",comment)
.then((res) => {
this.comments = res.data;
});
},
}
<div class="pos-add">
<button
#click="getArticleComments(article)"
type="button"
class="btn btn-link btn-sm">
Show comments
</button>
</div>
<!-- <div v-show="article.comments" class="container_comment"> -->
<div class="container_comment">
<ul class="list-group list-group comments">
<li
class="
list-group-item
fst-italic
list-group-item-action
comment
"
v-for="(comment, indexComment) in comments"
:key="indexComment"
>
{{ comment.comment_message }}
<!-- {{ comment.comment_message }} -->
</li>
</ul>
</div>
Your action getArticleComments does not return anything and I would avoid changing the action to return data. Instead remove the assignment to this.comments in home.vue
Actions do not return data, they get data, and call mutations that update your store.
Your store should have a getter that exposes the state, in this case the dataComments.
getters: {
dataComments (state) {
return state.dataComments;
}
}
Then in your home.vue you can use the helper mapGetters
computed: {
...mapGetters([
'dataComments'
])
}
You want your views to reference your getters in your store, then when any action updates them, they can be reactive.
More here: https://vuex.vuejs.org/guide/getters.html
As far as I see, you don't return any data in your getArticleComments action. To receive the comments you should return them, or even better, get them from your store data directly.
First make sure that you pass the response data to your mutation method:
getArticleComments: ({ commit }, dataArticles) => {
return new Promise(() => {
instance.get(`/comment/${dataArticles.article_id}`)
.then(function (res) {
commit('getComments', res.data);
})
.catch(function (error) {
console.log(error)
})
})
},
After dispatching you could either return the response data directly or you could access your store state directly. Best practice would be working with getters, which you should check in the vue docs.
getArticleComments(comment) {
this.$store
.dispatch("getArticleComments",comment)
.then((res) => {
// in your case there is no res, because you do not return anything
this.comments =
this.$store.state.dataComments;
});
},
I'm stuck to get the data from the database through Axios using Vue.js. In Vue.js developer tools I can get the data from my database like this:
But when I loop using v-for like this:
<template>
<div class="flex flex-col items-center py-4">
<NewPost></NewPost>
<Post v-for="(post,i) in posts.data" :post="post" :key="i"/>
</div>
</template>
<script>
import NewPost from "../components/NewPost";
import Post from "../components/Post";
export default {
name: "Newsfeed",
components: {
NewPost,
Post
},
data: () => {
return {
posts: null
}
},
mounted() {
axios.get('/api/posts').then(res => {
this.posts = res.data
console.log(this.posts)
}).catch(error => {
console.log('Unable to fetch posts')
})
}
}
</script>
<style scoped>
</style>
The console says
"[Vue warn]: Error in render: "TypeError: Cannot read property 'data'
of null"
found in
---> at resources/js/views/Newsfeed.vue
at resources/js/components/App.vue
"
I don't understand because in Vue.js developers tools I can get the data. Is the looping wrong? Thank you!
Init that nested field with an empty array like :
data: () => {
return {
posts: {
data:[]
}
}
},
Another answer is to add the loading variable like this
In the data :
data: () => {
return {
posts: null,
loading: true
}
}
In the mounted()
mounted() {
axios.get('/api/posts').then(res => {
this.posts = res.data
this.loading = false
console.log(this.posts)
}).catch(error => {
this.loading = false
console.log('Unable to fetch posts')
})
}
I am working with vue and here is my code
everything is working fine until I submitting the form. when I submit form and try to update emailForm -> tabs -> en -> data -> name then i got an error.
<template>
<el-form :model="emailForm.tabs" ref="emailForm" class="demo-emailForm" #submit="submitForm('emailForm')">
<div v-for="(lan, key, index) in emailForm.tabs">
<el-form-item :label="$t('Template Name')" >
{{lan.data.name}}
</el-form-item>
<el-form>
<template>
<script>
export default {
data() {
return {
emailForm: {
tabs: {
en: {
sortHeand: 'en',
title: 'English',
data: {
name: "ad",
subject: "asda",
html_code: 'asdad',
status: 0
}
}
}
}
}
},
methods: {
submitForm(formName) {
this.$refs[formName].validate(valid => {
if (valid) {
request({
url: this.getRoute(),
method: "post",
data: this[formName].tabs
})
.then(response => {
console.log(response)
})
}
});
},
}
}
</script>
Anyone can render this issue ?
You're trying to read property name from variable/object data but data is undefined so it can't read the property name from it.
I am trying to complete a CRUD application with Vuejs and Laravel. Right now I can add an article but cannot delete and I ssee this error in my console:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
The html inside the template is like the following:
<div class="card card-body"v-for="article in articles" :key="article.id">
<h3>{{ article.title }}</h3>
<p>{{ article.body }}</p>
<button #click="deleteArticle(article.id)" class="btn btn-danger">Delete</button>
</div>
Then inside the script I have this:
How can I make the delete work?
<script>
export default {
data(){
return{
articles: [],
article: {
id: '',
title: '',
body: ''
},
article_id: '',
pagination: {},
edit: false
}
},
created(){
this.fetchAllArticles();
},
methods: {
fetchAllArticles(){
fetch('/api/articles').then(res => res.json()).then(res => {
this.articles = res.data;
})
.catch(err => console.log(err));
},
deleteArticle(id){
if(confirm('Are you sure?')){
fetch('api/article/${id}', {
method: 'delete'
})
.then(res => res.json())
.then(data => {
alert('Article removed');
this.fetchAllArticles();
})
.catch(err => console.log(err));
}
}
}
}
</script>
If I type my url for the delete method I can view the data as you can see in the image:
My delete controller looks like this:
public function destroy($id)
{
// Get article
$article = Article::findOrFail($id);
if($article->delete()) {
return new ArticleResource($article);
}
}
From the netwok in the browser I see this:
Thanks in advance
I have never use fetch i love using axios, but through googling i found that you have to use not those symbols '' but those `` so:
fetch(`api/article/${id}`, {
method: 'delete'
})
From what I see in your console the API address is incorrect, should be 'api/article/' + id
I have been following the Stripe integration tutorial by Laracasts and it's become apparent to me that a lot has changed since Laravel 5.4 was released. I have been able to still find my way along but I have hit a bump trying to submit a payment form using Vue and Axios.
The product is being retrieved from a database and displayed in a select dropdown - this works. My issue is the data is not being properly sent to the store function in the PurchasesController. When I try to make a purchase the form modal appears fine, I fill it out with the appropriate test data and submit it, but in Chrome inspector I can see that /purchases returns a 404 error and when I check the network tab the error is: No query results for model [App\Product]
Here is the original Vue code:
<template>
<form action="/purchases" method="POST">
<input type="hidden" name="stripeToken" v-model="stripeToken">
<input type="hidden" name="stripeEmail" v-model="stripeEmail">
<select name="product" v-model="product">
<option v-for="product in products" :value="product.id">
{{ product.name }} — ${{ product.price /100 }}
</option>
</select>
<button type="submit" #click.prevent="buy">Buy Book</button>
</form>
</template>
<script>
export default {
props: ['products'],
data() {
return {
stripeEmail: '',
stripeToken: '',
product: 1
};
},
created(){
this.stripe = StripeCheckout.configure({
key: Laravel.stripeKey,
image: "https://stripe.com/img/documentation/checkout/marketplace.png",
locale: "auto",
token: function(token){
axios.post('/purchases', {
stripeToken: token.id,
stripeEmail: token.email
})
.then(function (response) {
alert('Complete! Thanks for your payment!');
})
.catch(function (error) {
console.log(error);
});
}
});
},
methods: {
buy(){
let product = this.findProductById(this.product);
this.stripe.open({
name: product.name,
description: product.description,
zipCode: true,
amount: product.price
});
},
findProductById(id){
return this.products.find(product => product.id == id);
}
}
}
</script>
And my PurchasesController.
<?php
namespace App\Http\Controllers;
use Log;
use App\Product;
use Illuminate\Http\Request;
use Stripe\{Charge, Customer};
class PurchasesController extends Controller
{
public function store()
{
Log::info("Product Info: " . request('product'));
Log::info("Stripe Email: " . request('stripeEmail'));
Log::info("Stripe Token: " . request('stripeToken'));
$product = Product::findOrFail(request('product'));
$customer = Customer::create([
'email' => request('stripeEmail'),
'source' => request('stripeToken')
]);
Charge::create([
'customer' => $customer->id,
'amount' => $product->price,
'currency' => 'aud'
]);
return 'All done';
}
}
I realise that product isn't being passed through to /purchases above so I have tried this:
axios.post('/purchases', {
stripeToken: token.id,
stripeEmail: token.email,
product: this.product
})
Unfortunately I still get the same No query results for model [App\Product] error even with that. Is there another/better way of passing data from Vue/Axios that I could use instead? If anyone is able to assist it would be much appreciated.
Thank you in advance.
Edit
The solution was to recast this to be a new variable and it started functioning again. Here is the relevant portion of the Vue Code that worked for me:
created(){
let module = this; // cast to separate variable
this.stripe = StripeCheckout.configure({
key: Laravel.stripeKey,
image: "https://stripe.com/img/documentation/checkout/marketplace.png",
locale: "auto",
token: function(token){
axios.post('/purchases', {
stripeToken: token.id,
stripeEmail: token.email,
product: module.product
})
.then(function (response) {
alert('Complete! Thanks for your payment!');
})
.catch(function (error) {
console.log(error);
});
}
});
},
Are you sure when assigning the product ID to data (using product: this.product) that this keyword is really your Vue instance? You might need to bind it manually calling .bind(this) on the .post(...) call.
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind