Vue js in laravel [closed] - laravel

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I'll post the code, I can't store the data in the tweets array, where am I wrong? i am using vue and laravel
<script>
export default {
mounted() {
this.recupera_post()
},
data(){
return{
tweets:[]
}
},
methods:{
async recupera_post(){
await axios.get('api/schedulepost')
.then(function(response){
console.log(response.data)
app.tweets=response.data
})
}
}
}
</script>

you just need to write this.tweets also you need to change your callback function to arrow function to allow you to access your state like this
async recupera_post(){
await axios.get('api/schedulepost')
.then((response) => {
console.log(response.data)
this.tweets = response.data
})
}
}

Related

Vue Route does not working. Laravel 8 + Vue [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I don't know what's wrong with my code or it issues on laravel 8?
router JS File
import Vue from 'vue'
import VueRouter from 'vue-router'
import FirstPage from './components/pages/FirstPage.vue'
Vue.use(VueRouter)
const routes = [
{ path: '/new-route', component: FirstPage }
]
export default new VueRouter({
mode: 'history',
routes
})
app JS File
require('./bootstrap');
window.Vue = require('vue')
import router from './router'
Vue.component('mainapp', require('./components/mainapp.vue').default)
const app = new Vue ({
el: '#app',
router
})
web PHP File
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TestController;
Route::get('/', function () {
return view('welcome');
});
Route::get('test', [TestController::class, 'test']);
Route::any('{slug}', function(){
return view ('error');
});
does any have an idea? or any suggestions. (It requires more details to be posted)
you need to use this in web.php
Route::any('{all}', [TestController::class, 'test'])
->where('all', '^(?!api).*$')
->where('all', '^(?!storage).*$');
or
Route::any('{all}',function(){
return view('main'); // it should be main blade file
})
->where('all', '^(?!api).*$')
->where('all', '^(?!storage).*$');
to work vue router without #
this code exclude api and storage url so both will work and other all route catch so vuejs do its magic

Vue Component not showing store data

I am building a trivia maker. I am currently working on the edit page for a question. The edit component, named EditQAForm, grabs the question and answers for that particular question and populates each of it's respective VueX store's form.
I am currently having trouble with the answers portion of this page. When the EditQAForm is mounted it calls the fetchQuestionAnswers, which retrieves all the answers for that particular question. It does this correctly, but then when I try to display any of the answers onto the page, it says that the form is empty despite me seeing in the Vue DevTools that it is not empty.
(Please note I deleted stuff that wasnt relevant to this. So assume all methods you see called do exist)
Here is the mounted for the EditQAForm:
mounted() {
//gets the params from the url
this.routeParams = this.$route.params;
//gets the answers that belong to this question
this.fetchQuestionAnswers(this.routeParams.question_id);
//not important for this problem
//get the question that needs to be edited
this.fetchQuestion(this.routeParams.question_id);
},
How I call it in the computed properties of the EditQAForm:
computed: {
...mapGetters('question', ['formQuestionRoundID', 'questions', 'questionFields']),
...mapGetters('answer', ['answerFields', 'answers']),
//Questions
questionForm: {
get() {
return this.questionFields;
},
},
//Answers
answerForm: {
get() {
return this.answerFields;
},
},
}
Here is the store for the answers
function initialState() {
return {
answers: [],
answer: null,
form: [
{
id: '',
title: '',
question_id: '',
round_id: '',
correct: false,
},
{
id: '',
title: '',
question_id: '',
round_id: '',
correct: false,
},
{
id: '',
title: '',
question_id: '',
round_id: '',
correct: false,
},
]
}
}
const getters = {
answers(state){
return state.answers;
},
answerFields(state){
return state.form;
},
loading(state){
return state.loading;
},
};
const actions = {
fetchQuestionAnswers({ commit, state }, question_id) {
console.log("Form outside axios:");
console.log(state.form);
commit('setLoading', true);
axios.get('/api/question/' + question_id + '/answers')
.then(response => {
commit('SET_ANSWERS_FORM', response.data);
commit('setLoading', false);
}).catch( error => {
console.log(error.response);
});
},
const mutations = {
SET_ANSWERS_FORM(state, answers){
for(let $i = 0; $i < answers.length; $i++)
{
state.form[$i] = {
id: answers[$i].id,
title: answers[$i].title,
question_id: answers[$i].question_id,
round_id: answers[$i].round_id,
correct: answers[$i].correct,
}
}
// state.answers = answers;
},
UPDATE_TITLE(state, payload){
state.form[payload.order].title = payload.title;
},
UPDATE_QUESTION_ID(state,payload){
state.form[payload.order].question_id = payload.questionID;
},
};
What I try outputting:
<div>
<h3 class="pb-3">Is first answer's title not empty?: {{!(answerForm[1].title === '')}}</h3>
<h3 class="pb-3">{{answerForm[0].title }}</h3>
<h3>{{answerForm}}</h3>
</div>
What shows on my screen, alongside what devtools tells me is inside the answerForm array:
I implemented the question portion in a very similar way. The only difference is that the form is not an array in the question store, but besides that it works fine. What am i doing wrong?
I think the problem is here:
state.form[$i] = {
If you use an index to update an array it won't trigger the reactivity system and you'll get a stale version of the rendered components. See https://v2.vuejs.org/v2/guide/list.html#Caveats
There are various ways to fix this. You could use Vue.set or alternatively just create am entirely new array.
Not entirely clear to me why you're doing all that copying in the first place rather than just using state.form = answers, which would also solve the problem.

Load current user with Vue/Axios in Laravel

Okay I'm trying to find the best way to load the current user into my vue app so that I can pull the username and ID from any other component or route.
Right now I've tried this:
app.js
new Vue({
el: '#app',
computed: {
user(data) {
return new Promise((resolve, reject) => {
axios.get('/current-user')
.then(response => {
resolve(response.data);
console.log(response.data);
})
.catch(error => {
reject(error.response.data);
});
});
}
},
router
});
It will log my user just fine, but I can't call #{{ user }} in any blade file. How exactly am I supposed to get the current user on app initialization?
Your user computed property returns Promise object not desired value.
Below is my proposition of solving your problem. You should be able to succesfully call #{{ user }} within your blade files. However to access user property in children components you are forced to use $parent.user property of theirs.
Personally I recommend you checking out Vuex which is made for such cases. It is centralized state storing solution allowing you to access (and manage) data from all over your app.
new Vue({
el: '#app',
data () {
return {
user: null
};
},
created () {
// As app intializes user is fetched and saved
this.fetchUser();
},
methods: {
fetchUser () {
axios.get('/current-user')
.then(response => {
this.user = response.data;
})
.catch(error => {
alert('Something went wrong');
console.error(error.response.data);
});
}
},
router
});

Create dynamic channels using Laravel echo and broadcasting

I'm trying to create a chat in which users can create 1 to 1 conversations or even group conversations. I'm using Laravel 5.5 and Vue.js.
From what I read from the documentation to join a chat with a wild card is possible:
Echo.join('chat.'{roomId})
//.here()
//.joining()
//.leaving()
.listen('MessagePosted', (e) => {
//Some action
});
});
and in routes/channels.php I should use
Broadcast::channel('chat.{roomId}', function ($user, $roomId) {
//some form of authentication
});
But where should I place the Echo function?
I'm creating the Vue app with
const app = new Vue({
el: '#app',
data: {
//Some arrays
},
methods: {
//some methods
},
created() {
//some axios functions to happen when it is created
Echo.join('chatroom')
//.here()
//.joining()
//.leaving()
.listen('MessagePosted', (e) => {
console.log(e);
this.messages.push({
message: e.message.message,
user: e.user
});
});
}
});
As you can see I used to create a general channel in which every instance created with #app would join. But I want to change that to join just a certain channel.
Easier than I thought.
Just created method that will be called whenever I wish to change the channel, for example, a different window chat. Place the function inside the methods
showThread(thread) {
Echo.leave(/*The last channel*/);
Echo.join(/*New room*/)
.listen('MessagePosted', (e) =>{/*actions*/}
Not sure if it the best practice to call it constantly but it works. If anyone finds this and has a question or suggestion I would gladly hear it.

Help needed in make custom module in kiosk(Laravel Spark)

We are new to Laravel Spark, we are trying to add custom module in kiosk
so we want one form in that module,we are following steps of below link
https://spark.laravel.com/docs/2.0/forms
We are define our vue component for form in our ROOT_DIR/resources/assets/js/app.js
by adding below code:
Vue.component('formexample', {
data()
{
return {
form: new SparkForm({
level_name: '',
level_status: ''
})
};
}
});
After set the view file we add method to our vue component in app.js(ROOT_DIR/resources/assets/js/app.js) file:
new Vue(require('laravel-spark'));
Vue.component('formexample', {
data()
{
return {
form: new SparkForm({
level_name: '',
level_status: ''
})
};
},
methods: {
register() {
Spark.post('/formexample', this.form)
.then(response => { console.log(response);
});
}
}
});
enter image description here
So our question is .we are follow the steps in wrong way ?? please suggest right way.
Also guide us for validation of forms and insert stuff into the database
Thankx in advance

Resources