Home  >  Article  >  Web Front-end  >  How does Vue know that the address bar has changed?

How does Vue know that the address bar has changed?

PHPz
PHPzOriginal
2023-04-13 10:44:081215browse

As a popular front-end framework, Vue.js (Vue for short) provides developers with some flexible routing management tools to facilitate page switching and control in single-page applications.

However, sometimes we need to make some responses when the routing address changes. For example, we want to render different content based on the parameters in the address, or display different navigation bars based on different routes.

So, how to monitor changes in the address bar in Vue? This article will introduce two methods:

1. Using Vue-Router’s route guard

Vue-Router is officially provided by Vue.js for managing SPA (Single-Page Application) routing plugin. Through Vue-Router, we can easily control routing across components.

Vue-Router provides the routing guard ([navigation guards](https://router.vuejs.org/zh/guide/advanced/navigation-guards.html)) function, which is the most popular feature of Vue-Router. One of the useful features. A route guard is a function that controls the navigation behavior of a route.

In the routing guard, we can use the beforeEach function to monitor routing changes. Whenever the route changes, this function will be called and passed in the three parameters to, from and next.

to is the target route to jump to, from is the current route, next is a function used to control the next What step to take. When we call the next function, the routing will continue to jump.

For example, suppose we want to monitor routing changes and render different text content based on the routing parameters id:

// 路由定义
const router = new VueRouter({
  routes: [
    {
      path: '/',
      component: Home
    },
    {
      path: '/post/:id',
      component: Post
    }
  ]
})

// Post组件定义
<template>
  <div>
    {{ postContent }}
  </div>
</template>

<script>
export default {
  data() {
    return {
      postContent: ''
    }
  },
  mounted() {
    this.fetchPostContent()
  },
  methods: {
    async fetchPostContent() {
      const id = this.$route.params.id // 从路由参数中获取id
      this.postContent = await fetch('/api/posts/' + id).then(response => response.json())
    }
  }
}
</script>

// 路由守卫监听
router.beforeEach((to, from, next) => {
  const id = to.params.id
  if (id !== undefined) { // 如果传入id参数,则修改文本内容
    next()
  } else { // 否则不进行跳转
    next(false)
  }
})

In the routing guard, we passto.params.idGet the routing parameter id and determine whether it exists. If it exists, continue to jump, otherwise do not jump.

In this way, when we enter /post/1 in the address bar, the Post component will obtain the content of the blog post with ID 1 and render it on the page. When we enter /post/ in the address bar, the jump will not occur.

Using Vue-Router's route guard is a simple and flexible method that can easily monitor changes in the address bar.

2. Use Vue’s watch attribute

In addition to Vue-Router, Vue itself also provides a responsive data binding mechanism. By monitoring data changes, we can make some responses when routing changes.

The responsive mechanism in Vue is implemented through the watch attribute. This property is used to monitor data changes on the Vue instance and execute the corresponding callback function when the data changes.

We can monitor changes in routing parameters and perform corresponding operations when the parameters change. For example:

// Post组件定义
<template>
  <div>
    {{ postContent }}
  </div>
</template>

<script>
export default {
  data() {
    return {
      postContent: ''
    }
  },
  watch: {
    // 监听路由参数id的变化
    '$route.params.id'(newId, oldId) {
      this.fetchPostContent(newId)
    }
  },
  mounted() {
    this.fetchPostContent(this.$route.params.id)
  },
  methods: {
    async fetchPostContent(id) {
      this.postContent = await fetch('/api/posts/' + id).then(response => response.json())
    }
  }
}
</script>

In this example, we listen for changes in $route.params.id and execute the corresponding callback function fetchPostContent when the id changes. When mounting for the first time, we also need to manually execute the fetchPostContent function to obtain the initial blog post content.

Using Vue's watch attribute can help us monitor changes in routing parameters and control the address bar.

In short, Vue provides a variety of methods to control routing behavior in single-page applications. Developers can choose the method that suits them according to their own needs.

The above is the detailed content of How does Vue know that the address bar has changed?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn