Accessing the Vue instance inside a component in Laravel Inertia - laravel

I am trying to parse a dynamic HTML with interpoltion inside them inside a Vue component in Inertia. My code looks something like below:
<template>
<div v-if="parsed" v-html="parsed"></div>
</template>
...
export default {
data(): return {
html: null,
name: null,
parsed: null,
},
mounted() {
this.name = "John"; // I got this from the API
this.html = "<h1>Hi, {{this.name}}!</h1>";
this.parse();
},
methods: {
parse() {
this.parsed = Vue.compile(html);
}
}
}
The error I'm getting is:
[Vue warn]: Error in v-on handler: "ReferenceError: Vue is not
defined"
My question is, how do I access the underlying Vue object inside the component. Thanks!

Check the cdn or js file version you have given.

Related

Vue & Laravel - Pass prop to a constant

I'm passing posts from controller to a Vue component:
public function show(Post $post)
{
return Inertia::render('Post/Show', ['post' => $post]);
}
In my vue file I have this:
<script>
import { ref, computed } from 'vue'
export default {
props: {
post: Object
}
}
const article = ref(post)
But this throws an error: Uncaught (in promise) ReferenceError: post is not defined.
How do I pass my post obj and assign it to the article constant?
I tried props.post but that isn't the solution, I'm very new to Vue and I'm mostly focused on backend stuff.

The global variable is not working with VueJS & Laravel

I have a global variable in app.blade.php like this>
<script>
window.App = {!! json_encode([
'apiToken' => Auth::user()->api_token,
]) !!};
</script>
I have in app.blade.php layouts a
and it has:
<script>
export default {
created() {
this.getRol();
},
methods: {
getRol() {
console.log(App.apiToken);
axios.get('/api/user?api_token='+App.apiToken)
.then(response => {
console.log(response);
this.rol_id = response.data.data.rol_id;
});
}
}
}
</script>
But I wonder why does it say this error?
[Vue warn]: Error in created hook: "ReferenceError: App is not defined"
And it's created globally.
Thanks
To create a "global variable" to be used in Vue, see LinusBorg's answer on the Vue forums here: https://forum.vuejs.org/t/global-variable-for-vue-project/32510/4
Contents of the post:
It’s not a good idea to use tru global variables in projects, to keep the global namespace clean.
Instead, create a small file, from where you can export any variable that you need to use in many places:
// variables.js
export const myVar = 'This is my variable'
export const settings = {
some: 'Settings'
}
// in your Vue
import { myVar, Settings } from './variables.js'

How to pass an object from axios catch block to parent component with Vue.js

I am using Laravel 7 and Vue.js 2.
I want to pass an object of validation errors from the catch block of an axios call to a parent component but for some reasons it doesn't work.
This is the code of the axios call:
runReport: function() {
let self = this;
const url = "api/get_report?room="+this.formReport['room']+"&participant="+this.formReport['participant']+"&start="+this.formReport['start']+"&end="+this.formReport['end'];
axios.get(url)
.then((response) => {
console.log(response.data.data);
this.meetingsReport = response.data.data;
this.$emit('passMeetings', this.meetingsReport);
this.$emit('success');
this.errors = {};
})
.catch(function(error) {
console.log(error.response.data);
self.errors = error.response.data;
alert(self.errors);
self.$emit('failure');
self.$emit('passErrors', self.errors); //problem
console.log('call ended');
});
}
This is the code in the parent component:
<template>
<div>
<report-meeting #passMeetings="onPassMeetings" #failure="displayTable=false" #success="displayTable=true"></report-meeting>
<hr>
<validated-errors :errorsMeeting="errorsMeeting" #passErrors="onPassErrors" v-if="displayTable===false"></validated-errors>
<table-report :meetingsSelected="meetingsSelected" v-if="displayTable===true"></table-report>
</div>
</template>
<script>
import TableReport from "./TableReport.vue"
import ReportMeeting from "./ReportMeeting.vue"
import ValidatedErrors from "./ValidatedErrors.vue"
export default {
components: {
'table-report': TableReport,
'report-meeting': ReportMeeting,
'validated-errors': ValidatedErrors
},
mounted() {
console.log('Component mounted.');
},
data: function() {
return {
displayTable: false,
meetingsSelected: {},
errorsMeeting: {}
}
},
methods: {
onPassMeetings(value) {
console.log(value);
this.meetingsSelected = value;
},
onPassErrors(value) {
console.log('errors passed'); //never used
this.errorsMeeting = value;
}
}
}
</script>
In the console I visualize no errors (except an 422 Unprocessable Entity). The strange thing is that the first emit works (failure), but the second one doesn't work (passErrors).
In the parent function onPassErrors I put a console.log that is never used so I suppose that the function is never called.
Can help?
This is likely caused by an event name mismatch, which can occur when using in-DOM templates because HTML attributes are automatically lower-cased (#passErrors becomes #passerrors in the DOM).
When using the development build of Vue, you'd see a warning in the browser's console:
[Vue tip]: Event "passerrors" is emitted in component but the handler is registered for "passErrors". Note that HTML attributes are case-insensitive and you cannot use v-on to listen to camelCase events when using in-DOM templates. You should probably use "pass-errors" instead of "passErrors".
This is not a problem in single file components (demo 1) or string templates (demo 2), but if you must stick with in-DOM templates, custom event names are recommended to be kebab-case:
<!-- Parent.vue -->
<MyComponent #pass-errors="onPassEvent" />
// MyComponent.vue
runReport() {
this.$emit('pass-errors', /*...*/)
}
demo 3

Create global method vue on app.js laravel

I want create global method to translate message using Laravel-JS-Localization
But when i call the method using vue mustache got an error like this:
Property or method "trans" is not defined on the instance but referenced during render.
Make sure that this property is reactive.
Here my laravel app.js code:
require('./bootstrap');
window.Vue = require('vue');
Vue.component('dashboard', require('./components/Dashboard').default);
const app = new Vue({
el: '#vue',
methods: {
trans: function (key) {
return Lang.get(key);
},
},
});
Dashboard.vue code :
<template>
<p>{{ trans('common.welcome') }}</p>
</template>
<script>
data () {
return {
name: '',
}
},
</script>
dashboard.blade.php code :
..........
<div class="col-9" id="vue">
<dashboard></dashboard>
</div> <!--c end col-8 -->
..........
I would probably go with creating a Plugin. For example
Vue.use({
install (Vue) {
Vue.prototype.$trans = Lang.get
}
})
Adding this to your app.js code before creating any components or new Vue({...}) will mean all your components will have access to the $trans method.
Alternatively, you can create a Global Mixin but these aren't strongly recommended.
Use global mixins sparsely and carefully, because it affects every single Vue instance created, including third party components
Vue.mixin({
methods: {
trans (key) {
return Lang.get(key)
}
}
})

how to change export const in vue js

I have const:
export const globalUser = new Vue({
created: function(){
this.getActualUser();
},
data: {
ActualUser: {name:'',meta:'',tipo:''}
},
methods:{
getActualUser: function(){
var urlMeta='usuarioActual';
axios.get(urlMeta).then(response=>{
this.ActualUser=response.data;
});
}
}
});
Now i'm importing that in a component of vue js
import {globalUser} from '../app.js'
Here is my data:
data:function(){
return {
usuarioActual:globalUser.ActualUser,
anotherData:{}
}
}
This returns me:
"usuarioActual": {
"name": "",
"meta": "",
"tipo": ""
}, the data is empty.
What i want is the returns me data after the method getActualUser run:
ActualUser: {name:'currentName',meta:'currentDat',tipo:'currentType'}
It works well:
axios.get(urlMeta).then(response=>{
this.ActualUser=response.data;
});
I did it in a wrong way, maybe it will work.
I get a different solution:
Instead of using data in components, i'm using "props".
I don't need to import, just called the props in the blade template of laravel, there i can use #elements from laravel.
Props in component:
props:{
usuario:String
},
Now i'm using that:
#extends('layouts.app')
#section('content')
<user-component usuario="{{ Auth::user()->name }}"></user-component>
#endsection
Works well, if you need more data u can add a function in the Model.
Now i can use that in my template of component
<template>
<tr v-if="{{usuario}} =='Admin'">

Resources