In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Vue development skills, I believe that many inexperienced people do not know what to do, so this article summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.
Routing parameter decoupling
Routing parameters are generally used within components, and most people do this:
Export default {methods: {getParamsId () {return this.$route.params.id}
The use of $route in a component makes it highly coupled to its corresponding route, thus limiting its flexibility by making the component available only on certain URL.
The right thing to do is to decouple through props
Const router = new VueRouter ({routes: [{path:'/ user/:id', component: User, props: true}]})
When the props property of the route is set to true, the params parameter can be received within the component through props
Export default {props: ['id'], methods: {getParamsId () {return this.id}
In addition, you can return props through function mode.
Const router = new VueRouter ({routes: [{path:'/ user/:id', component: User, props: (route) = > ({id: route.query.id})}]})
Documentation: router.vuejs.org/zh/guide/es...
Functional component
Functional components are stateless, they cannot be instantiated, and there are no lifecycles and methods. Creating functional components is also easy, as long as you add a functional declaration to the template. It is generally suitable for components that only depend on changes in external data, and rendering performance will be improved because of its light weight.
Everything the component needs is passed through the context parameter. It is a context object that views the document with specific properties. Where props is an object that contains all the bound properties.
Functional components:
{{item.title}}
{{item.content}}
The parent component uses:
Import List from'@ / components/List.vue' export default {components: {List}, data () {return {list: [{title: 'title', content:' content'}], currentItem:''}
Documentation: cn.vuejs.org/v2/guide/re...
Pattern penetration
It is common to modify the style of third-party components in development, but because of the style isolation of the scoped attribute, you may need to remove scoped or create another style. All of these practices have side effects (component style pollution, lack of elegance), and style penetration does not work until it is used in the css preprocessor.
We can use > or / deep/ to solve this problem:
Outer layer >. El-checkbox {display: block; font-size: 26px; .el-checkbox__label {font-size: 16px;}} / deep/. El-checkbox {display: block; font-size: 26px; .el-checkbox__label {font-size: 16px;}}
Advanced use of watch
1. Execute immediately
Watch is triggered only when listening for property changes, and sometimes we want watch to execute immediately after the component is created.
The way you might think of is to call it once in the create lifecycle, but this is not elegant, so maybe we can use this method:
Export default {data () {return {name: 'Joe'}}, watch: {name: {handler:' sayName', immediate: true}}, methods: {sayName () {console.log (this.name)}
Deep listening when listening to an object, the watch cannot be triggered when the internal properties of the object are changed. We can set depth listening for it:
Export default {data: {studen: {name: 'Joe', skill: {run: {speed:' fast'}, watch: {studen: {handler: 'sayName' Deep: true}}, methods: {sayName () {console.log (this.studen)}
two。 Trigger snooping
Execute multiple methods to set multiple items in the form of strings, functions, and objects using arrays:
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)}
Documentation: cn.vuejs.org/v2/api/#wat...
Watch listens for multiple variables
Watch itself cannot listen to multiple variables. However, we can return multiple variables that need to be monitored by calculating properties to the object, and then listen to the object to achieve "listening to multiple variables".
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}
Event parameter $event
$event is a special variable of the event object, which can provide us with more available parameters for implementing complex functions in some scenarios.
1. Primary event
Behaves the same as the default event object in the native event:
Export default {methods: {inputHandler (msg, e) {console.log (e.target.value)}
two。 Custom event
Behave as capturing values thrown from subcomponents in custom events
My-item.vue:
Export default {methods: {customEvent () {this.$emit ('custom-event',' some value')} copy the code
App.vue:
Export default {methods: {customEvent (index, e) {console.log (e) / / 'some value'}
Documentation:
Cn.vuejs.org/v2/guide/ev...
Cn.vuejs.org/v2/guide/co...
Two-way binding of custom components
Component model options:
Allows a custom component to customize prop and event when using v-model. By default, v-model on a component uses value as prop and input as event, but some input types such as checkboxes and check box buttons may want to use value prop for different purposes. Use the model option to avoid conflicts arising from these situations.
By default, input is used as an update event for bidirectional binding. You can update the binding value through $emit.
Export default {props: {value: {type: Boolean, default: false}}, methods: {switchChange (val) {this.$emit ('input', val)}
Modify model options for components and customize bound variables and events
Export default {model: {prop: 'num', event:' update'}, props: {value: {type: String, default:''}, num: {type: Number, default: 0}} Methods: {numChange () {this.$emit ('update', this.num++)}
Documentation: cn.vuejs.org/v2/api/#mod...
Listening component lifecycle
Usually we use $emit to monitor the component life cycle, and the parent component receives events for notification
Subcomponents:
Export default {mounted () {this.$emit ('listenMounted')}}
Parent component:
In fact, there is a simple way to use @ hook to listen to the life cycle of the component without making any changes within the component. Similarly, created, updated, and so on can also use this method.
Programmed event listener
For example, if you define a timer when a page is mounted, you need to clear the timer when the page is destroyed. That doesn't seem to be a problem. But if you take a closer look, the only function of this.timer is to be able to get the timer sequence number in beforeDestroy, which is of no use at all.
Export default {mounted () {this.timer = setInterval () = > {console.log (Date.now ())}, 1000)}, beforeDestroy () {clearInterval (this.timer)}}
It is best that only lifecycle hooks can access it if possible. This is not a serious problem, but it can be regarded as sundries.
We can solve this problem by destroying the life cycle of the $on or $once listening page:
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)})}}
After using this method, even if we create multiple timers at the same time, it does not affect the effect. Because they will be programmatically cleared independently after the page is destroyed.
Documentation: cn.vuejs.org/v2/guide/co...
Manually mount the assembly
In some requirements, manually mounting components allows us to implement them more elegantly. For example, a pop-up component is ideally used through imperative calls, like elementUI's this.$message. Instead of switching through state in the template, this implementation is really bad.
Let's start with the simplest example:
Import Vue from 'vue' import Message from'. / Message.vue' / / Construction subclass let MessageConstructor = Vue.extend (Message) / / instantiated component let messageInstance = new MessageConstructor () / / $mount can pass a selector string to indicate that it is mounted to the selector / / if no selector is passed in, it will be rendered as an element outside the document You can imagine that document.createElement () generates dom messageInstance.$mount () / / messageInstance.$el in memory and gets the dom element document.body.appendChild (messageInstance.$el).
The following implements a simple message pop-up window component
Message/index.vue:
{{item.content}} / / the default option const DefaultOptions = {duration: 1500, type: 'info', content:' this is a message!' ,} let mid = 0 export default {data () {return {notices: []}} Methods: {add (notice = {}) {/ / name logo is used to remove pop-up window let _ name = this.getName () / / merge option notice = Object.assign ({_ name}, DefaultOptions) Notice) this.notices.push (notice) setTimeout (() = > {this.removeNotice (_ name)}, notice.duration)}, getName () {return 'msg_' + (mid++)} RemoveNotice (_ name) {let index = this.notices.findIndex (item = > item._name = _ name) this.notices.splice (index, 1)}. Wrap {position: fixed Top: 50px; left: 50%; display: flex; flex-direction: column; align-items: center; transform: translateX (- 50%);} .message {--borderWidth: 3px; min-width: 240px; max-width: 500px; margin-bottom: 10px; border-radius: 3px; box-shadow: 00 8px # ddd; overflow: hidden;} .content {padding: 8px Line-height: 1.3;} .message.info {border-left: var (--borderWidth) solid # 909399; background: # F4F4F5;} .message.success {border-left: var (- borderWidth) solid # 67C23A; background: # F0F9EBE;} .message.error {border-left: var (--borderWidth) solid # F56C6C; background: # FEF0F0;} .message.messages {border-left: var (- borderWidth) solid # E6A23C Background: # FDF6EC;}
Message/index.js:
Import Vue from 'vue' import Index from'. / index.vue' let messageInstance = null let MessageConstructor = Vue.extend (Index) let init = () = > {messageInstance = new MessageConstructor () messageInstance.$mount () document.body.appendChild (messageInstance.$el)} let caller = (options) = > {if (! messageInstance) {init (options)} messageInstance.add (options)} export default {/ / return install Function for Vue.use registration install (vue) {vue.prototype.$message = caller}}
Main.js:
Import Message from'@ / components/Message/index.js' Vue.use (Message)
Use:
This.$message ({type: 'success', content:' success message prompt', duration: 3000})
Documentation: cn.vuejs.org/v2/api/#vm-...
Outer layer >. El-checkbox {display: block; font-size: 26px; .el-checkbox__label {font-size: 16px;}} after reading the above, have you mastered the Vue development skills? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.