update follow status after axios request in Vue - javascript

i need to update the follow an unfollow button after axios request
<template>
<div v-if="isnot">
<a href="#" #click.prevent="unfellow" v-if="isfollowing" >unFellow</a>
<a href="#" #click.prevent="fellow" v-else >Fellow</a>
</div>
</template>
My Methods
fellow () {
axios.post(`/#${this.follower}/follow/`)
},
unfellow () {
axios.post(`/#${this.follower}/unfollow/`)
},
}

A basic example:
fellow () {
var self = this;
axios.post(`/#${this.follower}/follow/`)
.then(function (response) {
self.isfollowing = true;
})
.catch(function (error) {
console.log( error.response.data);
});
},

Axios has a series of methods you can execute after the response arrives. In the case of a post call your structure can be something like this
axios.post(YOUR ROUTE)
.then(function (response) {
//executes after getting a successful response
// here you can change your 'isfollowing' variable accordingly
})
.catch(function (error) {
//executes after getting an error response
});

Fast way:
<template>
<div v-if="isnot">
<a href="#" #click.prevent="fellowUnfellow" v-if="isfollowing" >{{isfollowing ? "unFellow" : "Fellow"}}</a>
</div>
</template>
fellowUnfellow () {
axios.post(`/#${this.follower}/follow/`).then(function (r) {
this.isfollowing = !this.isfollowing;
})
}

Related

stocking api response.data in localStorage on click vuejs

My goal is to store a specific data in the localStorage when I click on a link
but log i get is either undefined or absolutely nothing.
<li v-for="(categorie, index) in categories" :key="index">
<a href="./currentCategory" #click.prevent="getCategory()">
<img class="categorie-img" :src="categorie.strCategoryThumb" >
<p>{{ categorie.strCategory }}</p>
</a>
</li>
data() {
return {
categories: []
}
},
methods: {
getAllCategories() {
axios
.get('https://www.themealdb.com/api/json/v1/1/categories.php')
.then((response) => {
console.log( response.data);
this.categories = response.data.categories;
}).catch(error => {
console.log(error);
alert("api can't be reached");
})
},
getCategory() {
localStorage.setItem('currentCategory', this.categorie.strCategory );
}
},
I am using this API https://www.themealdb.com/api/json/v1/1/categories.php
I guess this.categorie.strCategory is incorrect but i really cant figure it out
I also tried this.categories.strCategory
Try to pass category
#click.prevent="getCategory(categorie)
then save it
getCategory(cat) {
localStorage.setItem('currentCategory', cat );
}
Found the answer thanks to #Nikola Pavicevic
had to pass a category to the click event
#click.prevent="getCategory(categorie.strCategory)
and pass it to the function
getCategory(cat) {
localStorage.setItem('currentCategory', cat);
}

How to post from array mutiple request with axios in vuejs?

i try to post with axios from an array to an api php file and get the responses one by one not just one request. I read something about axios.all() but can't figure it out i am new to javascript.
<div id="app">
<center>
<div id="area">
<textarea v-model="sent" name="sent" id="sent" cols="30" rows="10" class="form-control">
</textarea>
<br>
<button v-on:click="insert" class="btn btn-default">Send</button>
</div>
<div id="good" v-for="message of messages">
<span><h2>Good</h2></span>
{{ message }}
</div>
</center>
</div>
And here is the vuejs code.
<script>
new Vue({
el:'#app',
data:{
sent:[],
messages:[]
},
methods:{
insert:function (){
const vm = this;
splitz.forEach(function(entry){
axios.post('/one.php', {
sent: vm.entry
}).then(response => {
vm.messages.push(response.data.onefinal) ;
console.log(response.data);
}
).catch(function(error){ console.log(error); });
}
}
},
computed:{
splitz: function () {
return this.sent.split('\n')
}
}
});
</script>
You can do it this way:
// Create an array of post requests from splitz array
var requests = splitz.map(entry => axios.post('/one.php', { sent: this.entry }))
// Send all requests using axios.all
axios.all(requests)
.then(results => results.map(response => response.data.onefinal))
.then(newMessages => {
console.log('New Messages:', newMessages)
this.messages.push.apply(this.messages, newMessages)
})
Edit: to send the requests one by one:
insert: function() {
var vm = this;
function sendRequest(arr, i) {
var entry = arr[i];
axios.post('/one.php', { sent: entry }).then(function (response) {
vm.messages.push(response.data.onefinal);
if (i < arr.length - 1) {
sendRequest(arr, ++i);
}
})
.catch(function (error) {
console.log(error);
});
}
sendRequest(this.splitz, 0);
}

How to Re-bind / Refresh Dom after ajax call in vuejs2 (like $scope.$apply in angularjs)?

I am using vue.js 2 with webpack template. i am new to vue.js.
i want to bind DOM after data is received in ajax call.
here in my code contains v-for in which the response html is need to bind with v-html="tHtml[index]" every time after data is received from api call.
What can be used to re-bind or refresh view/DOM as we use $scope.$apply() in angularjs.
home.vue
<template>
<div class="row" id="home">
<h3 v-if="msg"><span class="label label-warning">{{msg}}</span></h3>
</div>
<div v-for="obj in tdata">
<div v-html="tHtml[$index]"></div>
</div>
</div>
</template>
<script>
import appService from '../service'
import bus from '../service/bus'
export default {
created() {
appService.checkAuth();
console.log("service appService val: "+appService.user.authenticated);
//called after vue has been created
bus.$on('eventBusWithTopic', (data) => { //fetch event bus on ready to get data
//alert("event fetched! "+data.user_id);
console.log("event fetched! "+data.user_id);
this.searchedTopic = data.topic;
this.user_id = data.user_id;
bus.$off('eventBusWithTopic'); //un-bind event after use
//check details
})
},
data() {
return {
searchedTopic: '',
user_id: '',
tdata: {},
tHtml: []
}
},
methods: {
getdata(){
console.log("dfd "+this.user_id);
appService.getdata(this, this.user_id, this.searchedTopic).success((res) => {
//console.log(" res: "+JSON.stringify(res));
this.tdata = res.data;
if(this.tdata.length > 0){
//**GET HTML** // <<--==--==--==
for(var i=0;i<this.tdata.length;i++){
this.getTemplate(this.tdata[i].id_str);
}
}
if(res.success == 0)
this.msg = res.message;
}).error((e) => console.log("error while getting data: "+JSON.stringify(e)))
},
getTemplate(id){
this.$http.get("https://uqkcgyy8wb.execute-api..*****../user/"+id+"/getHtml", (resp) => {
//return resp.data.html;
this.tHtml[this.tHtml.length] = resp.data.html;
console.log(this.tHtml);
}).error((e) => console.log("error while getting html: "+JSON.stringify(e)))
}
}
}
</script>

Get the article's view times using Vue.js and Laravel 5.3

My thought process:
When the show page opens, get the article's id with JavaScript.
Check this id exist or not in cookie
If not exists, write it into cookie and send an ajax request, the backend updates view times.
If exists, do nothing.
Demo:
View:
<div class="card">
<div class="card-block text-xs-center">
<h5 class="card-title">{{$article->title}}</h5>
<hr class="m-y-2">
<h6 class="card-subtitle text-muted">date:{{$article->created_at->format('Y-m-d')}}
    views:{{$article->view_times}}</h6>
</div>
<div class="card-block">
<p class="card-text">{{$article->content}}</p>
</div>
</div>
Controller:
class ArticlesController extends Controller
{
//`show` method
public function show($id)
{
$article = Article::findOrFail($id);
return view('show', compact('article'));
}
//the method of updating view times.
public function statistics(Request $request)
{
$id = $request->input('id');
$article = Article::findOrFail($id);
$view_time=$article->view_time;
$article->view_time=$view_time+1;
$article->save();
}
}
JavaScript:
Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name=csrf-token]').getAttribute('content')
Vue.http.options.emulateJSON = true;
var vm = new Vue({
el: "body",
data: function(){
return{
id:[]
}
},
created() {
//1、Get the article's id.Do I have to send an ajax request? Is there any other way?
this.$http.get('article/get-id').then((response) => {
// success callback
this.id=response.data;
}, (response) => {
// error callback
});
//2、After Getting the `id`,check it in cookie,I don't know how to do it?
//3、If not exists,write it into cookie and send an ajax request,how to write the if() sentence?
if(){
var formData = new FormData();
var id=this.id;
formData.append('id',id);
this.$http.patch('article/statistics', formData,{
before(request) {
if (this.previousRequest) {
this.previousRequest.abort();
}
this.previousRequest = request;
}
}).then((response) => {
// success callback
}, (response) => {
// error callback
});
}
}
});
Questions:
There are three questions, shown as comments in JavaScript code above.

Passing an error message from controller to view with Backbone

I have the following error message available as HTML:
<div class="alert alert-error">
<div class="content">
<p>
<i class="fa fa-warning"></i>
User not found.
</p>
</div>
</div>
How can I display it for the user without losing good practices, in Backbone?
I mean, what's the best way to make my view render it with reliability?
When is this message displayed?
user.save({}, {
success: function(model, response) {
if (response.error) {
// hey, the message goes here!
}
}
});
You can extend Backbone View with a new method to display errors like this :
_.extend(Backbone.View.prototype, {
showError: function(message) {
// Here you render your error, may be like this : $('#errorInfo').html(message);
}
});
and in your view :
var self = this; // I assume that you are in the view
user.save({}, {
success: function(model, response) {
if (response.error) {
self.showError(/* things you want to pass */);
}
}
});
For me the best practice is to create an object errorMessageView
HTML :
<div id="errorInfo"></div>
JS :
var errorMessageView = Backbone.View.extend({
el: "#errorInfo",
initialize: function() {
},
renderInnerHTML: function(message) {
this.el.innerHTML = message;
}
});
var errorMessage = new errorMessageView ;
user.save({}, {
success: function(model, response) {
if (response.error) {
errorMessage.renderInnerHTML(response.error);
}
}
});

Categories