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')
Related
I have imported my full calender as plugin, its being displayed along with the events fetched from the database. If whenever i click on any event, i want to display details like title, start date in pop up dialog box but its displaying undefined.
<template>
<div class="page-wrapper">
<div class="container-fluid">
<FullCalendar :options='calendarOptions' />
</div>
</div>
</template>
<script>
import FullCalendar from '#fullcalendar/vue'
import interactionPlugin from '#fullcalendar/interaction'
import timeGridPlugin from '#fullcalendar/timegrid'
import dayGridPlugin from '#fullcalendar/daygrid'
export default {
components: {
FullCalendar
},
data() {
return {
event: '',
calendarOptions: {
plugins: [interactionPlugin, timeGridPlugin, dayGridPlugin],
initialView: 'dayGridMonth',
nowIndicator: true,
editable: true,
eventClick: this.handleEventClick,
dateClick:this.handleDateClick,
events: [],
}
}
},
mounted: function () {
this.getEventsDetail();
},
methods: {
handleEventClick: function (event) {
console.log(event);
},
handleDateClick: function () {
//alert('Date click');
},
getEventsDetail() {
this.$axios.$get('/api/projects/' + this.projectId + '/events')
.then(function (response) {
this.calendarOptions.events = response;
//console.log(this.calendarOptions.events);
}.bind(this));
},
}
}
</script>
if i write console.log(event.title) it gives me error as Cannot read properties of undefined (reading 'title') .
Please help me to get the details of event in a dialog box and present nicely.
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() }}');
}
}
I'm making new Vue 2 component that shows likes count after like button hitted. And get the error:
app.js:5060 [Vue warn]: Error in mounted hook: "ReferenceError: post_id is not defined"
<template>
<span>
<i class="fa fa-heart"></i> {{ likescount }}
</span>
</template>
<script>
import { bus } from '../bootstrap';
import 'vuejs-noty/dist/vuejs-noty.css'
export default {
props: ["post_id"],
data: function() {
return {
likescount: 0,
}
},
created(){
bus.$on('postliked', (data) => {
this.updatelikescount(post_id);
});
},
mounted : function() {
post_id = {};
this.updatelikescount(post_id);
},
methods: {
updatelikescount(post_id) {
axios
.get('/blog/post/likecount/' + post_id)
.then(response => {
this.likescount = response.data.data[0][0]
})
.catch(response => console.log(response.data));
},
}
};
</script>
this is my blade template
<likepostcount
:post_id={{ $post->id }}
></likepostcount>
When I open the Vue Dev Tools, I see the post_id = 4
It looks like you just need to add this.
mounted : function() {
this.post_id = {};
this.updatelikescount(this.post_id);
},
You code will always set the post_id to an empty object. You probably want to set a default value when you declare the props.
props: {
post_id: {
type: Object,
default: () => {}
}
},
mounted : function() {
this.updatelikescount(this.post_id);
},
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'm developing a function on my website where a user should be able to edit his or hers own topic using ckeditor 5 and a textarea. The textarea is placed inside a modal. However, when I try to prefill the textarea when a user pushes a button, nothing goes inside the textarea. I have tried the following:
var editor;
ClassicEditor
.create(document.querySelector('#edit-reply-modal'))
.then(editor => {
editor = editor;
})
$(".toggle-edit-modal").click(function(e) {
e.preventDefault();
editor.setData("<p>Testing</p>"));
$("#edit-reply-modal").html("<p>Testing</p>");
});
Any help is appreciated.
I see you have one ')' more than needed editor.data.set("<p>Testing</p>"));
If you still can't set data, than try to set data like this :
editor.data.set("<p>Testing</p>");
Html :
<!-- The editable element in the editor's DOM structure. -->
<div class="... ck-editor__editable ..." contenteditable="true">
<!-- Editable content. -->
</div>
vanilla Javascript :
// A reference to the editor editable element in the DOM.
const domEditableElement = document.querySelector( '.ck-editor__editable' );
// Get the editor instance from the editable element.
const editorInstance = domEditableElement.ckeditorInstance;
// Use the editor instance API.
editorInstance.setData( '<p>Hello world!<p>' );
Docs : https://ckeditor.com/docs/ckeditor5/latest/builds/guides/faq.html
HTML Code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.ckeditor.com/ckeditor5/24.0.0/classic/ckeditor.js"></script>
<textarea id="edit-reply-modal"><p>Old Data</p></textarea>
<button id="toggle-edit-modal">Fill New Data</button>
JAVASCRIPT Code:
let YourEditor;
ClassicEditor
.create(document.querySelector('#edit-reply-modal'))
.then(editor => {
window.editor = editor;
YourEditor = editor;
})
$('#toggle-edit-modal').on('click', function() {
YourEditor.setData('<p>This is the new Data!</p>');
})
let YourEditor;
ClassicEditor
.create(document.querySelector('#edit-reply-modal'))
.then(editor => {
window.editor = editor;
YourEditor = editor;
})
$('#toggle-edit-modal').on('click', function() {
YourEditor.setData('<p>This is the new Data!</p>');
})
button{
margin-top:20px;
padding: 5px;
color: white;
background: #00F;
border-radius: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.ckeditor.com/ckeditor5/24.0.0/classic/ckeditor.js"></script>
<textarea id="edit-reply-modal"><p>Old Data</p></textarea>
<button id="toggle-edit-modal">Fill New Data</button>
According to the documentation unlike ckeditor4 there is not any CKEDITOR.instances, so if you want to update your editor content, you can create a global instance of yor editor and then use setData() in order to update content by ajax.
Sample Code:
let myEditor;
ClassicEditor
.create(document.querySelector('#menuContent'), {
language: {
// The UI will be English.
ui: 'fa',
// But the content will be edited in Arabic.
content: 'fa'
},
placeholder: 'متن منو را وارد نمایید...'
})
.then(editor => {
window.editor = editor;
myEditor = editor;
})
.catch(err => {
console.error(err.stack);
});
function ShowMenuDetails(id) {
$.ajax({
url: '#Url.Action("MenuDetails", "Admin")',
type: 'POST',
data: JSON.stringify({ id: id }),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
cache: false,
success: function (data) {
$("#menuTitle").val(data.MenuTitle);
$("#order").val(data.MenuOrder);
myEditor.setData(data.MenuContent);
$("#myModal").modal();
},
error: function (err) {
alert(err);
},
statusCode: {
404: function (content) { alert(content); },
500: function (content) { alert(content); }
}
});
}