Vue3訪問頁面時自動獲取數據的方法實現
更新時間:2024年11月05日 09:29:12 作者:lewis_0
本文介紹了在Vue3中如何利用生命周期鉤子函數和定時器實現訪問頁面時自動獲取數據的方法,這種方法適用于需要在頁面加載時即時更新數據顯示的場景,感興趣的可以了解一下
1、使用生命周期鉤子函數
# 后端代碼--使用pywebview class Api: def greet(self): greet_text= 'pywebview and vue3' response = {} response['text'] = greet_text return response if __name__ == '__main__': # 前后端通信測試 api = Api() window = webview.create_window('Vue app in pywebview', './static/index.html', js_api=api) webview.start(debug=True)
<template> <div>{{ data }}</div> </template> <script> export default { data() { return { data: null }; }, created() { this.fetchData(); }, methods: { fetchData() { // 使用pywebview前后端通信 window.pywebview.api.greet().then(response=> { this.data= response['text']; }); } } }; </script>
2、使用定時器
<template> <div>{{ data }}</div> </template> <script> export default { data() { return { data: null, timer: null }; }, created() { this.fetchData(); this.timer = setInterval(this.fetchData, 5000); // 每5秒獲取一次數據 }, methods: { fetchData() { // 使用pywebview前后端通信 window.pywebview.api.greet().then(response=> { this.data= response['text']; }); }, cancelAutoUpdate() { clearInterval(this.timer); } }, beforeDestroy() { this.cancelAutoUpdate(); } }; </script>
到此這篇關于Vue3訪問頁面時自動獲取數據的方法實現的文章就介紹到這了,更多相關Vue3訪問頁面時自動獲取數據內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!