After the VUE2.x message jumps to the corresponding business page, the navigation bar changes accordingly.

The front end wants to implement the function of clicking the message title and then jumping to the corresponding business page, and the navigation bar also changes accordingly. In fact, the main problem lies in routing and communication between parent components and child components.

First look at the current component reference:

NoticeIcon.vue=>UserMenue.vue=>GlobalHeader.vue

NoticeIcon is the message component, UserMenue is the user's navigation bar component, and GlobalHeader is the website's standard navigation bar component.

First, let’s implement the problem of communication between child components and parent components.

NoticeIcon.vue=>UserMenue.vue=>GlobalHeader.vue

this.$emit("方法名",参数) //子组件调用父组件的方法,支持双向绑定

The this.$emit.event command will call the method of the parent component. Note that the method name must be consistent with the method of the parent component. Bind this method on the label of the parent component that references the child component. This is a two-way binding. When the child component calls the method of the parent component, after the variables in the parent component method are modified, the corresponding view of the parent component will also change accordingly.

//子组件NoticeIcon中的方法
comeTo(record){
      this.visible=false
      this.$parent.switchApp(record.appCode) //更新缓存中的路由表
      setTimeout(() => { //延迟300毫秒后执行,等待路由表更新完成
        this.$router.push(record.path) //跳转
        this.$emit("changeSelectedApp",[record.appCode])//菜单栏跟随路由变化,调用父组件UserMenue
        }, 300);
        
    }

Bind method in parent component UserMenue

<!--视图中引入子组件-->
<notice-icon class="action" @changeSelectedApp="changeSelectedApp"/>
//script中
import NoticeIcon from '@/../../NoticeIcon'

//method中声明同名的方法
   changeSelectedApp(defApp){
        this.$emit("changeSelectedApp",defApp) //参数传递给父组件,方法同上,通知父组件GlobalHeader做改变
      }

In the Menu of the GlobalHeader method, add the selectedKeys attribute, which is used to display the currently selected menu item.

<a-menu style="height: 55px; border-bottom: 0px;" mode="horizontal" :default-selected-keys="this.defApp" :selectedKeys="this.defApp">

//method中,被子组件调用,修改meau中当前被选择的菜单
      changeSelectedApp(defApp){
        this.defApp=defApp
      }

After the above operations, when the dynamic routing table is updated, use this.$router.push(path) command to jump to the specified business page, followed by communication between the child and parent groups, and the navigation bar can also be changed accordingly. .

Guess you like

Origin blog.csdn.net/weixin_43604220/article/details/128626264