I am new in VueJS, i want to check disk realtime using VueJS but my code not working for realtime, needed to resfresh the page, I don't know why
here is my script :
var vo = new Vue({
el: '.data_env',
data () {
return {
data : {}
}
},
mounted () {
axios
.get(BASE_URL+'clients/get_disk_size')
.then(response => (
this.data = response.data
))
}
})
Anyone can help me out ?
You need to refresh the page because mounted() executed only during creation of the component.
If you have variable and want to fetch a new data when this variable changed, you can use watch or computed. If you want to get a new data whenever it changed on server side you need to use websocket.
According to Vue lifecycle,if you want to fetch result on realtime you should put you code inside computed and watch property.
If any changes occur it will do two way binding with Html element and show changes without refreshing page
For More info go through this link - https://v2.vuejs.org/v2/guide/computed.html
Related
Currently I want to pass data from edit page to add page. So i pass the query using {path: '/test/admin/clinicvisit/add', query:{id:this.$route.params.id}}. I was able to pass the data to add page using the query however sometimes the data may not present when it refreshes a few times. Is there any possible way to make the data consistent stay in the add page ?
add.vue
async testRoute(){
let visitId = this.$route.query.id
if (visitId){
let clinicVisit = await this.api.medical.viewClinicVisit(visitId)
this.inputs = await this.api.medical.optionsClinicVisit()
this.$set(this.inputs.staff, "item_text", "username")
this.$set(this.inputs.staff, "item_value", "id")
this.$set(this.inputs.staff, "items", await this.api.profile.listStaff({}))
if(clinicVisit.staff){
this.$set(this.inputs.staff, "value", clinicVisit.staff)
this.$set(this.inputs.staff, "tmp_value", clinicVisit.staff_detail.name)
}
mounted()
{
this.testRoute()
}
This can be done in multiple ways.
Using a global store, You can use a library like Vuex to share the state between the components.
Using the Local Storage, if you want to preserve the data and keep saved after hard refreshing the page.
Using Session Storage, if you want to preserve the data and keep saved during the user session, but whenever the user close the browser tab it will be gone.
When you observe that the data is not present after a few refreshes, does it dissapear from the URL in your browser, or does it just not load?
If you want the data to stay more consistently, consider using localStorage
localStorage.setItem('item_text', 'username') //Save variable in browser data
let item_text = window.localStorage.getItem('item_text') //Get variable from browser data
EDIT:
If the URL is still present in the browser window, that sounds like a weird loading bug, where your code runs before the route is parsed by Vue.
You can try using a watcher instead of the "mounted" function:
watch: {
$route: {
immediate: true,
handler() {
this.testRoute()
}
}
}
I solved this error by setting a timeout function in my edit.vue.
handleCreate(event){
event.preventDefault();
this.$router.push({path: '/medical/admin/clinicvisit/add', query:{id:this.$route.params.id}},2000)
// now 'this' is referencing the Vue object and not the 'setTimeout' scope
this.loadClinicVisitData = true;
setTimeout(() => this.loadClinicVisitData = false,1000)
}
In our VueJS application, we are having few API's which are calling each and every time whenever the page reloads. In those API's. few response will never change and very few will rarely change. I planning to cache those API calls response and store it in a variable and use it whenever needed and reduce the number of requests when page reloads.
I am new to vueJS and not having any idea how to implement it. Is there anyway to achieve this in VueJS or Javascript? Any help would be most appreciated.
Sample HTML code,
<div class="col-sm-6">
<span>Is User Available? {{userInfo[is_user_available]}} </span>
<span> User Type : {{userType}} </span>
</div>
API call will be like below,
created: function () {
this.checkForUser();
},
methods: {
checkForUser: function() {
this.api.call('user_info', { username : this.username })
.then((response) => {
if (response) {
this.userInfo = response;
this.userType = this.userInfo['user_type'];
}
})
.catch((error) => {
this.userInfo.length = 0;
})
}
}
If you store the data in a regular Vuex store you will loose it on page refresh unless you use vuex-persistedstate plugin, which saves the store data on the local storage. (here is a working example)
Elaborating on #Mysterywood answer you can simply store it on local storage by yourself.
You can achieve that by simply doing
get:
const userType = window.localStorage.getItem('userInfo')
set:
window.localStorage.setItem('userInfo', response)
and remove:
window.localStorage.removeItem('userInfo')
There are few ways of doing this depending on how deep you want to go:
If you just want state to persists during the SPA session, you can do so:
Vuex if you would like to store globally accessible state/data. This allows your state to persist regardless of whether the components are destroyed/created.
Store it on your root-level Vue instance. If you're using the Vue CLI, this will be in your main.js. You can do something like so:
new Vue({
// ...
data: {
userType: {}
}
})
You can then access it via this.$root.userType. This is fine for small projects, but generally not recommended as things can get messy very quickly.
There's also EventBus, but again, this can get messy very quickly. EventBus is also deprecated in Vue3.
If you want to cache the response and access them again even after the user close their tab/browser, you will want to look into:
Cookies
localStorage
ServiceWorkers
check this, it can help :client-side storage in vuejs
Client-side storage is an excellent way to quickly add performance gains to an application. By storing data on the browser itself, you can skip fetching information from the server every time the user needs it. While especially useful when offline, even online users will benefit from using data locally versus a remote server. Client-side storage can be done with cookies, Local Storage (technically “Web Storage”), IndexedDB, and WebSQL (a deprecated method that should not be used in new projects).
I tried it with this method
useEffect(() => {
async function getUserData() {
var userData = await firebase.firestore().doc("ingredients/" + user.uid).get();
var labels = []
userData.data().ingredients.forEach(ingredient => {
labels.push(ingredient.label)
})
setUserIngredients(labels)
setUserRecipes(userData.data().recipes)
}
getUserData()
fetchRecipes(userIngredients)
}, [])
but it does not load when I use the app I need to save the file on my computer before it fetches the data. I'm using expo to debug the app on my smartphone. I want it to fetch the data when I go to the screen or when my app is starting
You can use loader when data is being fetching and hide it when data is fetched !
also if you want instant data fetch even before rendering screen ,then it is not the good approach if you really want it then do data fetch in custom constructor!
i.e
const [constructorHasRun, setConstructorHasRun] = useState(false);
and call fetch API in this constructor
const constructor = () => {
if (constructorHasRun) return;
// fetch API
setConstructorHasRun(true);
};
Hope You wants it and helped !
For these cases, I recommend saving data in Redux states is helping your app seems fast and you can access it when you need it.
Also, if you don't use Redux, you can save your data in SQLite because it seems your data about recipes, and update your data in the splash screen.
That's just another solution...
Im using vue.js with nuxt.js, I'm just still confused as when to use Data VS Async Data. Why would I need to use Async data when I just have data that just displays on the page?
I have a data object of FAQ's and just want to display the data without doing anything with it. What are the benefits of using the asyncData? Or what are the cases or best use of them?
Should I display list data such as this as async by default if using data such as this inside of my component?
Data
data:() => ({
faqs:[
{"title":"faq1"},
{"title":"faq2"},
{"title":"faq3"},
]
}),
asyncData
asyncData(context) {
return new Promise((resolve, reject) => {
resolve({
colocationFaqs:[
{"title":"faq1"},
{"title":"faq2"},
{"title":"faq3"},
]
});
})
.then(data => {
return data
})
.catch(e => {
context.error(e);
});
},
asyncData happes on the serer-side. You cant access browser things like localStorage or fetch() for example but on the ther hand you can access server-side things.
So why should you use asyncData instead of vue cycles like created?
The benefit to use asyncData is SEO and speed. There is this special context argument. It contains things like your store with context.store. Its special because asyncData happens on server-side but the store is on the client side usually. That means you can get some data and then populate your store with it and somewhere else you display it. The benefit of this is that its all server-side and that increase your SEO so for example the google crawler doesnt see a blank page
why would I need to pre render it when it is going to be displayed
anyway
Yes for us it doesnt matter if i send 1 File to the client and it renders all data like in SPA's or if its pre-rendered. But it doesnt matter for the google crawler. If you use SPA mode the crawler just sees a blank page. You can discoverd it too. Go to any SPA website and click right-click and inspect you will see thats there only 1 Div tag and few <script> tags. (Dont press F12 and inspect like this thats not what i mean).
I am making a note taking app and it is in the early prototyping stages, so I just want to hack together something that will work for myself.
My text editor is built using Quill, and I'm using Vue to structure the whole application. Currently, I don't have a back end, so no server.js.
I would like my application to be able to save the information that I put in the editor, and reload the information whenever I rebuild the app.
I checked out the autosave option provided by Quill here
But I'm not sure what to do with $.post and where to post it.
Can I simply post it to a local .json file?
What is the best thing to save in my case? The example was logging changes, what am I supposed to do with changes?
I apologize beforehand for the lack of clarity in my question, as I don't know exactly what I should be asking to achieve what I want.
Any advice is appreciated.
So if I understood correctly, what you're asking is how to implement quilljs' auto save feature when you have no server. But, you've already answered your own questions.
A simple way to do it would be saving the document into a local json file. But I don't know if you can do that using js.
Another way of doing it, is to save the content to the browser's local storage and loading the data every time you load the app.
var Delta = Quill.import('delta');
var quill = new Quill('#editor-container', {
modules: {
toolbar: true
},
placeholder: 'Compose an epic...',
theme: 'snow'
});
// Store accumulated changes
var change = new Delta();
quill.on('text-change', function(delta) {
change = change.compose(delta);
});
// Save periodically
setInterval(function() {
if (change.length() > 0) {
console.log('Saving changes', change);
// Save the entire updated text to localStorage
const data = JSON.stringify(quill.getContents())
localStorage.setItem('storedText', data);
change = new Delta();
}
}, 5*1000);
// Check for unsaved data
window.onbeforeunload = function() {
if (change.length() > 0) {
return 'There are unsaved changes. Are you sure you want to leave?';
}
}
Then inside your vue component's mounted(), use the following to fetch the saved data:
const data = JSON.parse(localStorage.getItem('storedText'));