I don't usually post unless i get frustrated. I have been using Imperavi Article and unable to use it with VueJS. Following is the code for sending CSRF-TOKEN, but i keep getting error 419, token miss match. I am unable to solve this issue. I've tried every way possible and got exausted.
Following is my code.
<template>
<div>
<article-editor :config="configOptions" :name="name"></article-editor>
</div>
</template>
<script>
export default {
props: ["name"],
data() {
return {
configOptions: {
subscribe: {
"upload.before.send": function(event) {
var xhr = event.get("xhr");
var token = document.head.querySelector(
"[name=csrf-token]"
).content;
xhr.setRequestHeader("X-CSRF-Token", token);
}
},
plugins: ["blockcode", "reorder"],
editor: {
focus: true
},
image: {
upload: "/admin/blog/images/upload"
}
}
};
}
};
</script>
<style></style>
Here is the error im getting.
"message": "CSRF token mismatch.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\HttpException",
Try this
subscribe: {
'autosave.before.send': function(event) {
var xhr = event.get('xhr');
xhr.setRequestHeader('X-CSRF-Token', '{{ csrf_token() }}');
},
'upload.before.send': function(event) {
var xhr = event.get('xhr');
xhr.setRequestHeader('X-CSRF-Token', '{{ csrf_token() }}');
}
}
Related
I have a text area as below:
<textarea class="from-control" name="body" id="body" v-html="pageForm.body" v-model="pageForm.body" rows="5" style="width:100%"></textarea>
Script:
<script>
export default {
components: {},
data() {
return {
pageForm: new Form({
body: '',
}),
};
},
props: [],
mounted() {
},
methods: {
update() {
let loader = this.$loading.show();
this.pageForm.patch('/api/frontend/google-map/')
.then(response => {
toastr.success(response.message);
loader.hide();
})
.catch(error => {
loader.hide();
helper.showErrorMsg(error);
});
},
}
}
</script>
I am sending an <iframe> from the <textarea> via axios patch request as <iframe src="some url"></iframe>
But in the laravel controller I receive $request->body = ""
Any ideas how do I achieve this?
Note:Form binding is working fine, but get empty value in Laravel Controller
I am currently creating a website with laravel and i created a comment system with vue. I managed to post comments successfully but i am having a problem with editing and deleting a specific comment. I am trying to somehow retrieve the id of each comment so i can create a method similar to the postComment() i have in the picture below to delete or edit the specific comment. Does anyone have an idea how to do that?
Thanks in advance
This is my post page which has the post and the attached comments
<script>
const app = new Vue({
el:'#root',
data: {
comments: {},
commentBox: '',
post: {!! $post->toJson() !!},
user: {!! Auth::check() ? Auth::user()->toJson() : 'null' !!},
},
mounted() {
this.getComments();
},
methods: {
getComments(){
axios.get('/api/posts/'+this.post.id+'/comments')
.then((response) => {
this.comments = response.data
})
.catch(function (error) {
console.log(error);
});
},
postComment(){
axios.post('/api/posts/'+this.post.id+'/comment', {
api_token: this.user.api_token,
text: this.commentBox
})
.then((response) => {
this.comments.unshift(response.data);
this.commentBox = '';
})
.catch(function (error) {
console.log(error);
});
},
}
});
</script>
In order to edit or delete a comment. You need the id of that comment. I create a very rough UI below for deleting. Updating requires a bit more complicated handling, but you get the idea:
<ul>
<!-- If the comments is an object, pls use Object.values(comments) -->
<li v-for="comment in comments">{{comment.text}} <button #click="deleteComment(comment.id)">Delete</button>
</ul>
<script>
const app = new Vue({
// ...
methods: {
deleteComment(commentId) {
// ...
}
}
});
</script>
You have to use the PUT request for upating and Delete for deleting data. I edited your code.
<script>
const app = new Vue({
el:'#root',
data: {
comments: {},
commentBox: '',
post: {!! $post->toJson() !!},
user: {!! Auth::check() ? Auth::user()->toJson() : 'null' !!},
},
mounted() {
this.getComments();
},
methods: {
deleteComments(){
axios.delete('/api/posts/'+this.post.id+')
.then((response) => {
console.log('Success")
})
.catch(function (error) {
console.log(error);
});
},
updateComment(){
axios.put('/api/posts/'+this.post.id, this.comments)
.then((response) => {
console.log('Success")
})
.catch(function (error) {
console.log(error);
});
},
}
});
</script>
I believe your back-end delete api route is api/posts/{post}
I'm using laravel-vue-i18n-generator package to handle text translation in vuejs component in my laravel project. I've set up app.js like below:
import VueInternationalization from 'vue-i18n';
import Locale from './vue-i18n-locales.generated';
Vue.use(VueInternationalization);
const lang = 'fa';
const i18n = new VueInternationalization({
locale: lang,
messages: Locale
});
const app = new Vue({
el: '#app',
i18n,
});
And in component:
<template>
<a href="#" class="tip" title="" :title="$t('component.delete.title')" #click.prevent="deleteAction">
<i :class="icon"></i>
</a>
</template>
<script>
import swal from 'sweetalert';
import axios from 'axios';
export default {
inject: ['$i18n'],
props:{
endpoint: {
type: String,
required: true,
},
icon: {
type: String,
default: 'fa fa-trash'
},
message: {
type: String,
default: this.$i18n.t('component.delete.are_you_sure'),
},
confirm: {
type: String,
default: this.$i18n.t('component.delete.confirm'),
},
cancel: {
type: String,
default: this.$i18n.t('component.delete.cancel'),
},
success: {
type: String,
default: this.$i18n.t('component.delete.success'),
},
failed: {
type: String,
default: this.$i18n.t('component.delete.failed'),
},
},
mounted() {
console.log(this);
},
methods:{
deleteAction(){
const vm = this;
swal({
text: this.message,
buttons: {
catch: {
text: this.confirm,
value: "delete",
},
cancel: this.cancel
},
dangerMode: true
}).then(name => {
if (!name) return false;
axios.delete(vm.endpoint)
.then(function (response) {
swal( vm.$i18n.t('component.delete.congrats'),vm.success, 'success').then(() => {
location.reload();
});
})
.catch(function (error) {
swal( vm.$i18n.t('component.delete.error'), vm.failed, 'error');
});
});
}
}
}
</script>
<style scoped>
</style>
Fortunately $t('component.delete.title') works correctly on template part, but in script part, I've got this error:
Uncaught TypeError: Cannot read property 't' of undefined
Where do I go wrong?
This worked for me inside the script part of a component:
this.$t('message')
In vue.js if you get an error like
"_vm.translate is not a function"
It is most probably that you havent import the i18n package which contains translate method.This error occures sometimes when you try to add translate using v-bind to html attributes. Example:
<a-form-item class="mb-0" :label="`${translate('person_name.firstname')}`">
following steps can solve the error.
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.0/vue.js"></script>
<script lang="ts">
import { translate, i18n } from '#/i18n';
#Component({
components: {
AgIconBase
},
methods:{
translate
}
})
</script>
This works for me.
I have a locales folder with index.js importing the two language files im using,
in this file add.
global.$t = Vue.t
Referred to in the script part directly as
return $t('backend.faq.main')
I have a component called "TextInput":
<template>
<q-input
v-model="content"
#input="handleInput"
color="secondary"
:float-label="floatLabel" />
</template>
<script>
import { QInput, QField } from "quasar-framework/dist/quasar.mat.esm";
export default {
props: ['floatLabel', 'value'],
data () {
return {
content: this.value
}
},
components: {
'q-field': QField,
'q-input': QInput,
},
methods: {
handleInput(e) {
this.$emit('input', this.content)
}
}
}
</script>
I used this component in another component:
<template>
<card card-title = "Edit Skill">
<img slot="img" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAaCAYAAACpSkzOAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAJeSURBVEhLzZVPSFRRGMVnKopI+odghFjWQDD05v8/dGCEaFEhbnwIQQTVol2rCHElQog7lwm6qdy0jBJpWQvBImgTEqGYoKIDYhS4qt9n38Qb5973ni7KA2fuPd937jt35t33JrKvUCqVjmaz2XI8Hm8qFArHmT8KS/ytehk7UqlUHPOzTCbzA36EDroNbsEnQcS/zFjWy5mRy+VuYaxiHIDNWo4wl6ANlb5g/VvfIAw3ZDfQ0dJfWIKi8uE4zil6LuuKon2DEonEMZpL6XT6ipbqsDOIi12EH/AnisViC/MqfK49exCN+xheqWyAN0huNN5FOAnlF/gMh+l3Sp+5b9AUu+tT2QBvEKfwMPMemXPR28wfy7wG3yCaa8lk8rzKBniDgmANkgCa6yqN8AYx3sX/xsB+6TOag2iM0phQaYQ3CL88V+5OUrefOp6byzSq+Xz+jJaM4AC049vEf8GPcv+MQRSn4UOVRnBIcixchfN4v1r4jf4vwmTj9UGIq/BLLBY7oiUj8IyxeEilEWymG88M0yj+WQI7/nQAhV6ac4xdWjKCRXfwzMMR/MMm0nvK+BO+gCvoE7p8G1GK9yguMG4/1TYQdg2f8U3tJdd5YH1M+NrnMFRV7hoE9MhfikpfHMC8xU5Oqg4NNnmWTW7K/5WW/IFZ3lcZlaHBBgfhmMpgYH5Jzk2VocG69/C6ymBglrf3u93+fKxb5aBcUhkM13UPEjTOwu+MtYfwtbatwL8B645yKHB6TrPDNIvlxflJy1bsOagGFpf/SZDcK4JKKq0gpKtSqRxS+b8QifwGm+z/Ksto7VkAAAAASUVORK5CYII=">
<form class="clearfix" slot="form">
<bim-text v-model="skill.name" :floatLabel="input_label"></bim-text>
<q-btn
#click="edit"
icon="save"
size="14px"
color="secondary"
label="Save" />
</form>
</card>
</template>
<script>
import { QBtn } from "quasar-framework/dist/quasar.mat.esm";
import { Card, TextInput } from "../../base";
import router from '../../../routes/routes';
export default {
data: function () {
return {
id: this.$route.params.id,
skill: {
name: ''
},
input_label: 'Skill Name'
}
},
components: {
'card': Card,
'bim-text': TextInput,
'q-btn': QBtn
},
methods: {
edit: function(){
axios.patch('/api/skills/'+this.id, {
name: this.skill.name,
}, { headers: { Authorization: 'Bearer '.concat(localStorage.getItem('token')) } })
.then(response => {
alert('success');
router.push({ name: "IndexSkills"});
}).catch(error => {
console.log('dd');
});
}
},
mounted() {
axios.get("/api/skills/"+this.id, { headers: { Authorization: 'Bearer '.concat(localStorage.getItem('token')) } })
.then(response => {
this.skill = response.data.data;
}).catch(error => {
alert('error')
});
}
}
</script>
<style scoped>
.q-btn{
float: right;
margin-top: 20px;
}
</style>
As you can see, I created an skill object with empty property called name and I made an axios request to get the specified object using its id. In then function of the axios request skill should be updated but what happened was that the v-model still empty.
What would be the problem here? and how can I solve it?
Thanks in advance.
You only assign v-model value (value property) to your content variable on initialization (data() method, which is only called on component initialization). You have no code that can react to value (v-model) change, that would update the content variable.
You should create a watch for value, and then set this.content = this.value again.
PS: Also, try instead of this
this.skill = response.data.data;
do this
this.skill.name = response.data.data.name;
I think I messed something up with the csrf_field() but I did push the X-CSRF-TOKEN... I had a 419 error before but brought myself more into trouble...
The error
- POST /betaling 500
- Uncaught (in promise) Response {url: "/betaling", ok: false, status: 500, statusText: "Internal Server Error", headers: Headers
Header
<script>
var Cityofcompanies = {
csrfToken: "{{ csrf_token() }}",
stripeKey: "{{ config('services.stripe.key') }}"
};
Routes
Route::post('betaling', 'PaymentController#store')->name('payment');
App.js
window.Vue = require('vue');
require('vue-resource');
Vue.http.interceptors.push((request, next) => {
request.headers.set('X-CSRF-TOKEN', Cityofcompanies.csrfToken);
next();
});
Vue.component('CheckoutForm',
require('./components/CheckoutForm.vue'));
CheckoutForm.vue
<template>
<form action="/betaling" method="POST">
<input type="hidden" name="stripeToken" v-model="stripeToken">
<input type="hidden" name="stripeEmail" v-model="stripeEmail">
<button type="submit" #click.prevent="buy">Abonneer</button>
</form>
</template>
<script>
export default {
data() {
return {
stripeEmail: '',
stripeToken: ''
};
},
created() {
this.stripe = StripeCheckout.configure({
key: Cityofcompanies.stripeKey,
image:"https://stripe.com/img/documentation/checkout/marketplace.png",
locale: "auto",
currency: "eur",
token: (token) => {
this.stripeToken = token.id;
this.stripeEmail = token.email;
this.$http.post('/betaling', this.$data);
//.then(response => alert('Bedankt voor het abonneren!'));
}
});
},
methods: {
buy() {
this.stripe.open({
name: "Abonneer voor 1 jaar",
description: "Professional Version",
amount: 5000,
});
}
}
}
</script>
Show.blade.php
<div id="checkout">
<checkout-form></checkout-form>
</div>
<script>
window.onload = function () {
const app = new Vue({
el: '#checkout'
});
}
</script>
<script src="https://checkout.stripe.com/checkout.js"></script>
You'll need to look at the logs for the /betaling endpoint to see what the error might be here.