vue 组件监听页面切换_vue监听url参数变化实现跳转当前页面组件复用并实现dom数据刷新解决方案...

本文介绍了如何在Vue中解决组件复用问题,通过监听URL变化,在页面切换时实现组件数据的刷新。关键步骤包括在子路由组件中创建、watch '$route'、调用fetchData方法获取新数据,并使用Vuex的count状态来判断是否需要重新加载。同时,父组件提供reload方法控制router-view的显示与隐藏,以达到刷新效果。
摘要由CSDN通过智能技术生成

解决思路:

1、子路由组件监听URL变化

a、created函数中:

created: function () {

var self = this

self.fetchData()

this.$store.state.count = 0 //在中央状态管理区中添加一个count值来标识是否重新加载,当页面每次加载完后把count值重新设置为0

},

b、watch函数中:

watch: {

'$route': 'fetchData'

},

c、methods函数中:

methods:{

fetchData () {

console.log('路由发生变化...')

let deptid = typeof (this.$route.query.id) === 'undefined' ? this.$store.state.deptid : this.$route.query.id

let deptName = typeof (this.$route.query.deptName) === 'undefined' ? this.$store.state.deptName : this.$route.query.deptName

let company = typeof (this.$store.state.company) === 'undefined' ? this.$route.params.company : this.$store.state.company

let from = typeof (this.$route.query.from) === 'undefined' ? this.$store.state.from : this.$route.query.from

let count = this.$store.state.count

this.deptName = deptName

this.deptid = deptid

this.company = company

this.$http.post('/dept', {

'pid': deptid,

'deptName': deptName,

'company': company

}).then((data) => {

this.depts = data.depts

this.peoples = data.people

if (from === 'dept' && count === 0) {//请求成功并且count状态为0的时候才从新加载

this.$store.state.count = 1//发生重新加载的时候要把状态改为1

this.reload()//调用父组件的刷新路由方法

}

})

},

}

d、引入父组件暴露的方法

export default{

inject: ['toggleDrawer', 'setMenu', 'reload'],//reload为父组件暴露的方法可调用

}

2、父组件写一个方法控制路由跳转刷新

a、//v-if绑定一个data值

data () {

return {

title: '',

link: '',

isRouterAlive: true

}

},

b、提供一个方法来改变data值控制router-view展示与隐藏

methods:{

reload () {

this.isRouterAlive = false

this.$nextTick(function () {

this.isRouterAlive = true

})

},

}

c、将路由刷新方法暴露出去,这样子组件就可以直接调用reload方法了

export default{

provide () {

return {

toggleDrawer: this.toggleDrawer,

setMenu: this.setMenu,

reload: this.reload

}

},

}

注:页面路由结构 Manager为父组件 Dept为子组件要进行当前页面跳转并刷新数据

{

path: '/Manager',

name: 'manager',

component: Manager,

children: [

{

path: 'managerindex',

name: 'managerindex',

component: ManagerIndex

},

{

path: 'company',

name: 'company',

component: Company

},

{

path: 'dept',

name: 'dept',

component: Dept

}

]

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值