search
HomeWeb Front-endJS TutorialImmediate use of watch in vue project

Immediate use of watch in vue project

Jun 09, 2018 am 11:38 AM
vuetechnology sharing

This time I will bring you the immediate use of watch in the vue project. What are the precautions for the immediate use of watch in the vue project. The following is a practical case, let's take a look.

I also wrote this in the project. For example, if there is a request that needs to be executed once before it is initialized, and then monitor its changes, many people write like this:

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

We can write the above as follows:

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

2. Component registration is worth learning from

Generally, our components are written as follows:

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

There are generally three steps,

The first step is introduction,

the second step is registration,

the third step is formal use,

This is also the most common and common way of writing. However, this writing method is classic. There are many components that need to be introduced and registered multiple times, which is very annoying.

We can use webpack to create our own (module) context using the require.context() method to achieve automatic dynamic require components.

The idea is: in main.js under the src folder, use webpack to dynamically package all the required basic components.

The code is as follows:

import Vue from 'vue'
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'
// Require in a base component context
const requireComponent = require.context(
 ‘./components', false, /base-[\w-]+\.vue$/
)
requireComponent.keys().forEach(fileName => {
 // Get component config
 const componentConfig = requireComponent(fileName)
 // Get PascalCase name of component
 const componentName = upperFirst(
  camelCase(fileName.replace(/^\.\//, '').replace(/\.\w+$/, ''))
 )
 // Register component globally
 Vue.component(componentName, componentConfig.default || componentConfig)
})

In this way, we only need the third step to introduce components:

<baseinput></baseinput>
<basebutton>
 <baseicon></baseicon>
</basebutton>

3. Simplify the introduction of modules in vuex

For vuex, we output the store as follows:

import auth from './modules/auth'
import posts from './modules/posts'
import comments from './modules/comments'
// ...
export default new Vuex.Store({
 modules: {
  auth,
  posts,
  comments,
  // ...
 }
})

We need to introduce a lot of modules, and then register them in Vuex.Store~~

Simplified The method is similar to the above, and also uses require.context() to read the file. The code is as follows:

import camelCase from 'lodash/camelCase'
const requireModule = require.context('.', false, /\.js$/)
const modules = {}
requireModule.keys().forEach(fileName => {
 // Don't register this file as a Vuex module
 if (fileName === './index.js') return
 const moduleName = camelCase(
  fileName.replace(/(\.\/|\.js)/g, '')
 )
 modules[moduleName] = {
        namespaced: true,
        ...requireModule(fileName),
       }
})
export default modules

In this way, we only need the following code:

import modules from './modules'
export default new Vuex.Store({
 modules
})

Four , Delayed loading of routing

Regarding the introduction of vue, I have mentioned it before in the technical points and summary of vue project reconstruction, which can be done through require or import() method to dynamically load components.

{
 path: '/admin',
 name: 'admin-dashboard',
 component:require('@views/admin').default
}

or

{
 path: '/admin',
 name: 'admin-dashboard',
 component:() => import('@views/admin')
}

Load the route.

5. Router key component refresh

The following scene really breaks the hearts of many programmers... First of all, let’s acquiesce. Vue-router is used to implement routing control. Suppose we are writing a blog website and the requirement is to jump from /post-haorooms/a to /post-haorooms/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) {
  // ...
 }
}

Solution: Add a unique key to router-view, so that even if it is a public component, as long as the URL changes, it will be re- Create this component.

<router-view></router-view>

Note: From my personal experience, this is generally used in sub-routes, so as not to avoid a large number of redraws. Assuming that this attribute is added to the root directory of app.vue, then every time you click to change the address, it will be redrawn. , it’s still not worth the gain!

6. The only component root element

The scenario is as follows:

(Emitted value instead of an instance of Error)
Error compiling template:


- 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.

There can only be one p in the template, not as above Then 2 p are parallel.

For example, the following code:

<template>
 <li>
  <router-link>
   {{ route.title }}
  </router-link>
 </li>
</template>

will report an error!

We can use the render function to render

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

    7. Component packaging and event attribute penetration issues

    当我们写组件的时候,通常我们都需要从父组件传递一系列的props到子组件,同时父组件监听子组件emit过来的一系列事件。举例子:

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

    这样写很不精简,很多属性和事件都是手动定义的,我们可以如下写:

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

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

    $listeners包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器。它可以通过 v-on="$listeners" 传入内部组件。

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

    推荐阅读:

    脚手架与热刷新、热加载

    Vue怎样进行局部作用域 & 模块化

    The above is the detailed content of Immediate use of watch in vue project. 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
    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.

    From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

    The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

    JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

    Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

    Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

    JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

    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

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Tools

    SecLists

    SecLists

    SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

    EditPlus Chinese cracked version

    EditPlus Chinese cracked version

    Small size, syntax highlighting, does not support code prompt function

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    SublimeText3 English version

    SublimeText3 English version

    Recommended: Win version, supports code prompts!

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool