vue-router?導航完成后獲取數(shù)據(jù)的實現(xiàn)方法
created:實例已經(jīng)創(chuàng)建完成之后被調(diào)用。在這一步,實例已完成以下的配置:數(shù)據(jù)觀測(data observer),屬性和方法的運算, watch/event 事件回調(diào)。然而,掛載階段還沒開始,$el 屬性目前不可見。
使用生命周期的 created() 函數(shù),在組件創(chuàng)建完成后調(diào)用該方法。
created(){
// 組件創(chuàng)建完成后獲取數(shù)據(jù)
// 此時data已經(jīng)被監(jiān)聽了
this.fetchData();
},
watch:{
'$route':'fetchData'
},
methods:{
fetchData(){
this.error = null;
this.post = null;
this.loading = true;
this.$axios.get('http://127.0.0.1:8888/post')
.then(res=>{
this.loading = false;
console.log(res.data);
this.post = res.data;
})
.catch(err=>{
this.error = err.toString();
})
}
}完整代碼如下:
<div id="app"><div>
<!-- 導航完成后獲取數(shù)據(jù),讓我們在數(shù)據(jù)獲取期間可以展示loading....狀態(tài) -->
<script type="text/javascript" src="./vue.js"></script>
<script type="text/javascript" src="./axios.js"></script>
<script type="text/javascript" src="./vue-router.js"></script>
<script type="text/javascript">
var Index = {
template:`
<div>我是首頁</div>
`
};
var Post = {
data(){
return{
loading:false,
error:null,
post:null
}
},
template:`
<div>
<div class='loading' v-if='loading'>
loading...
</div>
<div class='error' v-if='error'>
{{error}}
</div>
<div class='content' v-if='post'>
<h2>{{post.title}}</h2>
<p>{{post.body}}</p>
</div>
</div>
`,
created(){
// 組件創(chuàng)建完成后獲取數(shù)據(jù)
// 此時data已經(jīng)被監(jiān)聽了
this.fetchData();
},
watch:{
'$route':'fetchData'
},
methods:{
fetchData(){
this.error = null;
this.post = null;
this.loading = true;
this.$axios.get('http://127.0.0.1:8888/post')
.then(res=>{
this.loading = false;
console.log(res.data);
this.post = res.data;
})
.catch(err=>{
this.error = err.toString();
})
}
}
}
var router = new VueRouter({
routes:[
{
path:'/index',
name:'index',
component:Index
},
{
path:'/post',
name:'post',
component:Post
}
]
});
var App = {
template:`
<div>
<router-link :to = "{name:'index'}">首頁</router-link>
<router-link :to = "{name:'post'}">我的博客</router-link>
<router-view></router-view>
</div>
`
};
Vue.prototype.$axios = axios;
new Vue({
el:'#app',
template:`<App/>`,
components:{
App
},
router
});
</script>到此這篇關于vue-router 導航完成后獲取數(shù)據(jù)的文章就介紹到這了,更多相關vue-router 獲取數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
前端Vue?select下拉框使用以及監(jiān)聽事件詳解
由于前端項目使用的是Vue.js和bootstrap整合開發(fā),中間用到了select下拉框,這篇文章主要給大家介紹了關于前端Vue?select下拉框使用以及監(jiān)聽事件的相關資料,需要的朋友可以參考下2024-03-03
vue 修改 data 數(shù)據(jù)問題并實時顯示的方法
今天小編就為大家分享一篇vue 修改 data 數(shù)據(jù)問題并實時顯示的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08
Vue中如何實現(xiàn)在線預覽word文件、excel文件
這篇文章主要介紹了Vue中如何實現(xiàn)在線預覽word文件、excel文件,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07

