search
HomeWeb Front-endJS TutorialWatchers, components and routing control in Vue.js

This time I will bring you Watchers, components and routing control in Vue.js. What are the precautions for Watchers, components and routing control in Vue.js? The following is a practical case, let's take a look.

For most people, after mastering a few basic APIs of Vue.js, they can already develop front-end websites normally. But if you want to use Vue to develop more efficiently and become a Vue.js master, then you must seriously study the five tricks I will teach you below.

The first move: Watchers that simplify complexity

Scene restoration:

created(){
  this.fetchPostList()
},
watch: {
  searchInputValue(){
    this.fetchPostList()
  }
}

When the component is created, we get the list once and listen to the input at the same time Frame, it is very common to re-obtain the filtered list every time a change occurs. Is there any way to optimize it?

Move analysis:

First of all, in watchers, you can directly use the literal name of the function; secondly, declaring immediate: true means that it will be executed immediately when the component is created.

watch: {
  searchInputValue:{
    handler: 'fetchPostList',
    immediate: true
  }
}

Second move: once and for all component registration

Scene restoration:

import BaseButton from './baseButton'
import BaseIcon from './baseIcon'
import BaseInput from './baseInput'
export default {
 components: {
  BaseButton,
  BaseIcon,
  BaseInput
 }
}
<baseinput></baseinput>
<basebutton>
 <baseicon></baseicon>
</basebutton>

We wrote a bunch of basic UI components, and then every time we When you need to use these components, you must first import and then declare the components, which is very tedious! Adhering to the principle of being lazy if you can, we must find ways to optimize!

Move analysis:

We need to use the artifact webpack and use the require.context() method to create our own (module) context to achieve automatic dynamic require components. This method takes 3 parameters: the folder directory to search, whether its subdirectories should also be searched, and a regular expression to match files.

We add a file called global.js in the components folder, and use webpack to dynamically package all the required basic components in this file.

import Vue from 'vue'
function capitalizeFirstLetter(string) {
 return string.charAt(0).toUpperCase() + string.slice(1)
}
const requireComponent = require.context(
 '.', false, /\.vue$/
  //找到components文件夹下以.vue命名的文件
)
requireComponent.keys().forEach(fileName => {
 const componentConfig = requireComponent(fileName)
 const componentName = capitalizeFirstLetter(
  fileName.replace(/^\.\//, '').replace(/\.\w+$/, '')
  //因为得到的filename格式是: './baseButton.vue', 所以这里我们去掉头和尾,只保留真正的文件名
 )
 Vue.component(componentName, componentConfig.default || componentConfig)
})

Finally we import 'components/global.js' in main.js, and then we can use these basic components anytime and anywhere without manually introducing them.

Third move: Router key that pulls out all the stops

Scene restoration:

The following scene really broke the hearts of many programmers. .. First of all, by default, everyone uses Vue-router to implement routing control.

Suppose we are writing a blog website and the requirement is to jump from /post-page/a to /post-page/b. Then we surprisingly discovered that the data was not updated after the page jumped? ! The reason is that vue-router "intelligently" discovered that this is the same component, and then it decided to reuse this component, so the method you wrote in the created function was not executed at all. The usual solution is to monitor changes in $route to initialize the data, as follows:

data() {
 return {
  loading: false,
  error: null,
  post: null
 }
}, 
watch: {
 '$route': {
  handler: 'resetData',
  immediate: true
 }
},
methods: {
 resetData() {
  this.loading = false
  this.error = null
  this.post = null
  this.getPost(this.$route.params.id)
 },
 getPost(id){
 }
}

The bug is solved, but is it too inelegant to write like this every time? Adhering to the principle of being lazy if you can, we hope that the code will be written like this:

data() {
 return {
  loading: false,
  error: null,
  post: null
 }
},
created () {
 this.getPost(this.$route.params.id)
},
methods () {
 getPost(postId) {
  // ...
 }
}

Move analysis:

So how can we achieve such an effect? ​​The answer is to add a router-view unique key, so that even if it is a public component, as long as the URL changes, the component will be recreated. (Although some performance is lost, infinite bugs are avoided). At the same time, note that I set the key directly to the full path of the route, killing two birds with one stone.

<router-view></router-view>

The fourth trick: the omnipotent render function

Scene restoration:

Vue requires that each component can only have one root element , when you have multiple root elements, vue will report an error to you

<template>
 <li>
  <router-link>
   {{ route.title }}
  </router-link>
 </li>
</template>
 ERROR - Component template should contain exactly one root element. 
  If you are using v-if on multiple elements, use v-else-if 
  to chain them instead.

Move Analysis:

Is there a way to resolve it? The answer is yes, but this time we need Use the render() function to create HTML, not template. In fact, the advantage of using js to generate html is that it is extremely flexible and powerful, and you do not need to learn to use vue's instruction API with limited functions, such as v-for and v-if. (reactjs completely discards the template)

functional: true,
render(h, { props }) {
 return props.routes.map(route =>
  
  •         {route.title}       
  •  ) }

    The fifth move: high-level components that can win without any moves

    Key points: This move is infinitely powerful, please Be sure to understand

    When we write components, we usually need to pass a series of props from the parent component to the child component, and at the same time, the parent component listens to a series of events emitted from the child component. For example:

    //父组件
    <baseinput>
    </baseinput>
    //子组件
    <template>
     <label>
      {{ label }}
      <input>
     </label>
    </template>

    has the following optimization points:

    1.每一个从父组件传到子组件的props,我们都得在子组件的Props中显式的声明才能使用。这样一来,我们的子组件每次都需要申明一大堆props, 而类似placeholer这种dom原生的property我们其实完全可以直接从父传到子,无需声明。方法如下:

    <input>

    $attrs包含了父作用域中不作为 prop 被识别 (且获取) 的特性绑定 (class 和 style 除外)。当一个组件没有声明任何 prop 时,这里会包含所有父作用域的绑定,并且可以通过 v-bind="$attrs" 传入内部组件——在创建更高层次的组件时非常有用。

    2.注意到子组件的@focus=$emit('focus', $event)"其实什么都没做,只是把event传回给父组件而已,那其实和上面类似,我完全没必要显式地申明:

    <input>
    computed: {
     listeners() {
      return {
       ...this.$listeners,
       input: event => 
        this.$emit('input', event.target.value)
      }
     }
    }

    $listeners包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器。它可以通过 v-on="$listeners" 传入内部组件——在创建更高层次的组件时非常有用。

    3.需要注意的是,由于我们input并不是BaseInput这个组件的根节点,而默认情况下父作用域的不被认作 props 的特性绑定将会“回退”且作为普通的 HTML 特性应用在子组件的根元素上。所以我们需要设置inheritAttrs:false,这些默认行为将会被去掉, 以上两点的优化才能成功。

    相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

    推荐阅读:

    极度简介执行vue.watch

    vue axios调用接口时请求超时

    The above is the detailed content of Watchers, components and routing control in Vue.js. 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
    From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

    JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

    Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

    Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

    The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

    C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

    JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

    JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

    JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

    The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

    Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

    Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

    Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

    Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

    Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

    Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    MantisBT

    MantisBT

    Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

    ZendStudio 13.5.1 Mac

    ZendStudio 13.5.1 Mac

    Powerful PHP integrated development environment