Table of Contents
1. Routing parameter decoupling " >1. Routing parameter decoupling
2. Functional component" >2. Functional component
3. Style scope" >3. Style scope
4. Advanced use of watch" >4. Advanced use of watch
5.watch monitors multiple variables" >5.watch monitors multiple variables
6. Event parameter $event" >6. Event parameter $event
7. Programmed event listener" >7. Programmed event listener
Home Web Front-end Vue.js [Organization and Sharing] 8 Practical Vue Development Tips

[Organization and Sharing] 8 Practical Vue Development Tips

Feb 24, 2023 pm 07:29 PM
vue

This article compiles and shares 8 great Vue development skills, including routing parameter decoupling, functional components, style scope, advanced use of watch, watch monitoring multiple variables, etc. I hope it will be helpful to everyone!

[Organization and Sharing] 8 Practical Vue Development Tips

1. Routing parameter decoupling

Usually routing parameters are used in components, most people Will do the following things.

export default {
    methods: {
        getParamsId() {
            return this.$route.params.id
        }
    }
}
Copy after login

Using $route in a component results in a strong coupling to its corresponding route, limiting the flexibility of the component by restricting it to certain URLs. The correct approach is to decouple it through props.

const router = new VueRouter({
    routes: [{
        path:  /user/:id ,
        component: User,
        props: true
    }]
})
Copy after login

After setting the props attribute of the route to true, the component can receive params parameters through props inside the component. [Related recommendations: vuejs video tutorial, web front-end development]

export default {
    props: [ id ],
    methods: {
        getParamsId() {
            return this.id
        }
    }
}
Copy after login

You can also return props through functional mode.

const router = new VueRouter({
    routes: [{
        path:  /user/:id ,
        component: User,
        props: (route) => ({
            id: route.query.id
        })
    }]
})
Copy after login

2. Functional component

Functional component is stateless, it cannot be instantiated, and it does not have any life cycle or methods. Creating functional components is also as simple as adding a functional declaration to your template. It is generally suitable for components that only rely on external data changes, and improves rendering performance due to its lightweight. Everything the component needs is passed through context parameters. It is a context object, see the documentation for specific properties. props here is an object containing all bound properties.

<template functional>
    <div class="list">
        <div class="item" v-for="item in props.list" :key="item.id" @click="props.itemClick(item)">
            <p>{{item.title}}</p>
            <p>{{item.content}}</p>
        </div>
    </div>
</template>
Copy after login

Parent component usage

<template>
    <div>
        <List :list="list" :itemClick="item => (currentItem = item)" />
    </div>
</template>
Copy after login
import List from  @/components/List.vue
export default {
    components: {
        List
    },
    data() {
        return {
            list: [{
                title:  title ,
                content:  content
            }],
            currentItem:
        }
    }
}
Copy after login

3. Style scope

It is common to modify the style of third-party components during development, but Due to the style isolation of scoped attributes, you may need to remove scoped or create a new style. These practices have side effects (component style pollution, lack of elegance), and are implemented using style penetration in the CSS preprocessor. We can use>>> or /deep/ to solve this problem:

<style scoped>
Outer layer >>> .el-checkbox {
  display: block;
  font-size: 26px;

  .el-checkbox__label {
    font-size: 16px;
  }
}
</style>
Copy after login
<style scoped>
/deep/ .el-checkbox {
  display: block;
  font-size: 26px;

  .el-checkbox__label {
    font-size: 16px;
  }
}
</style>
Copy after login

4. Advanced use of watch

watch Triggered when the listener property changes. Sometimes we want the watch to be executed immediately after the component is created. One way that might come to mind is to call it once during the creation lifecycle, but that's not an elegant way to write it, so maybe we could use something like this.

export default {
    data() {
        return {
            name:  Joe
        }
    },
    watch: {
        name: {
            handler:  sayName ,
            immediate: true
        }
    },
    methods: {
        sayName() {
            console.log(this.name)
        }
    }
}
Copy after login

Deep Listening

When listening to an object, when the properties inside the object change, watch will not be triggered, so We can set up deep monitoring for it.

export default {
    data: {
        studen: {
            name:  Joe ,
            skill: {
                run: {
                    speed:  fast
                }
            }
        }
    },
    watch: {
        studen: {
            handler:  sayName ,
            deep: true
        }
    },
    methods: {
        sayName() {
            console.log(this.studen)
        }
    }
}
Copy after login

Trigger the listener to execute multiple methods

Using arrays, you can set multiple forms, including strings, functions, and objects.

export default {
    data: {
        name:  Joe
    },
    watch: {
        name: [
             sayName1 ,
            function(newVal, oldVal) {
                this.sayName2()
            },
            {
                handler:  sayName3 ,
                immaediate: true
            }
        ]
    },
    methods: {
        sayName1() {
            console.log( sayName1==> , this.name)
        },
        sayName2() {
            console.log( sayName2==> , this.name)
        },
        sayName3() {
            console.log( sayName3==> , this.name)
        }
    }
}
Copy after login

5.watch monitors multiple variables

watch itself cannot monitor multiple variables. However, we can "listen to multiple variables" by returning an object with a computed property and then listening to that object.

export default {
    data() {
        return {
            msg1:  apple ,
            msg2:  banana
        }
    },
    compouted: {
        msgObj() {
            const { msg1, msg2 } = this
            return {
                msg1,
                msg2
            }
        }
    },
    watch: {
        msgObj: {
            handler(newVal, oldVal) {
                if (newVal.msg1 != oldVal.msg1) {
                    console.log( msg1 is change )
                }
                if (newVal.msg2 != oldVal.msg2) {
                    console.log( msg2 is change )
                }
            },
            deep: true
        }
    }
}
Copy after login

6. Event parameter $event

$event is a special variable of the event object, which provides us with More parameters are available to implement complex functions. Native Events: Behaves the same as the default event object in Native Events.

<template>
    <div>
        <input type="text" @input="inputHandler( hello , $event)" />
    </div>
</template>
Copy after login
export default {
    methods: {
        inputHandler(msg, e) {
            console.log(e.target.value)
        }
    }
}
Copy after login

Custom event: In the custom event, it is expressed as capturing the value thrown from the child component.

export default {
    methods: {
        customEvent() {
            this.$emit( custom-event ,  some value )
        }
    }
}
Copy after login
<template>
    <div>
        <my-item v-for="(item, index) in list" @custom-event="customEvent(index, $event)">
            </my-list>
    </div>
</template>
Copy after login
export default {
    methods: {
        customEvent(index, e) {
            console.log(e) //  some value
        }
    }
}
Copy after login

7. Programmed event listener

For example, define a timer when the page is mounted and needs to be cleared when the page is destroyed timer. This doesn't seem to be a problem. But looking closer, the only purpose of this.timer is to be able to get the timer number in beforeDestroy, otherwise it is useless.

export default {
    mounted() {
        this.timer = setInterval(() => {
            console.log(Date.now())
        }, 1000)
    },
    beforeDestroy() {
        clearInterval(this.timer)
    }
}
Copy after login

It is best to only access lifecycle hooks if possible. This is not a serious problem but can be considered confusing. We can solve this problem by using or once to listen for page life cycle destruction:

export default {
    mounted() {
        this.creatInterval( hello )
        this.creatInterval( world )
    },
    creatInterval(msg) {
        let timer = setInterval(() => {
            console.log(msg)
        }, 1000)
        this.$once( hook:beforeDestroy , function() {
            clearInterval(timer)
        })
    }
}
Copy after login

使用这种方法,即使我们同时创建多个定时器,也不影响效果。这是因为它们将在页面被销毁后以编程方式自动清除。8.监听组件生命周期通常我们使用 $emit 监听组件生命周期,父组件接收事件进行通知。

子组件

export default {
    mounted() {
        this.$emit( listenMounted )
    }
}
Copy after login

父组件

<template>
    <div>
        <List @listenMounted="listenMounted" />
    </div>
</template>
Copy after login

其实有一种简单的方法就是使用@hook 来监听组件的生命周期,而不需要在组件内部做任何改动。同样,创建、更新等也可以使用这个方法。

<template>
    <List @hook:mounted="listenMounted" />
</template>
Copy after login

(学习视频分享:vuejs入门教程编程基础视频

The above is the detailed content of [Organization and Sharing] 8 Practical Vue Development Tips. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

React vs. Vue: Which Framework Does Netflix Use? React vs. Vue: Which Framework Does Netflix Use? Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to use vue traversal How to use vue traversal Apr 07, 2025 pm 11:48 PM

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values ​​for each element; and the .map method can convert array elements into new arrays.

See all articles