In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Editor to share with you what skills to use Vue, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
The data does not respond. There may be a problem with the usage.
A few days ago, a friend sent me a piece of code, and then said that Vue has bug, he clearly wrote no problem, why the data does not respond, it must be Vue bug? I felt that he was more powerful than you Yuxi, so I ignored him. But it is true that sometimes we encounter unresponsive data during development, so what should we do? For example, the following code:
User name: {{userInfo.name}} user gender: {{userInfo.sex}} official account: {{userInfo.officialAccount}} add official account export default {data () {return {userInfo: {name: 'Zijun', sex: 'male'} Methods: {/ / add the user's official account handleAddOfficialAccount () {this.userInfo.officialAccount = 'play at the front end'}} here
In the above code, we want to add the official account attribute to the user information, but it does not take effect after it is added by this.userInfo.officialAccount = 'play at the front end'. Why?
This is because within Vue, data response is achieved by using the getter,setter method of each key of the Object.definePrototype listening object, but by this method, existing attributes can only be monitored, and the new properties cannot be monitored, but I just want to listen. What do you say? The editor below provides four ways. If there are more ways, please let me know in the comments section below.
1. Define the attributes that should be added in advance in data
For example, the official account above, I can define it in userInfo in advance, so that it is not a new attribute, like the following
Data () {return {userInfo: {name: 'Zijun', sex: 'male', / / I define officialAccount:''}} in advance.
two。 Directly replace userInfo
Although I can't add new attributes to userInfo, because userInfo is already defined, I can just modify the value of userInfo directly, so I can also write like this
This.userInfo = {/ / copy the original userInfo to the new object through the extension algorithm. This.userInfo, / / add a new attribute officialAccount: 'play at the front end'}
3. Use Vue.set
In fact, both of the above methods are suspected of cheating. In fact, for new attributes, Vue officially provides a new method, Vue.set, to solve the problem that new attributes cannot trigger data response.
Vue.set method definition
/ * * object to be modified by target * name of attribute to be added by prpertyName * attribute value to be added by value * / Vue.set (target, propertyName, value)
Using Vue.set, the above code can be modified to
Import Vue from 'vue' / / add the user's official account handleAddOfficialAccount () {Vue.set (this.userInfo,'officialAccount',' frontend play')} here.
But every time you need to use the set method, you have to introduce Vue, which is very troublesome, so for simplicity, Vue mounts the set method on the prototype chain of Vue, that is, Vue.prototype.$set = Vue.set, so you can use this.$set instead of Vue.set directly inside the Vue component.
This.$set (this.userInfo,'officialAccount', 'have something to play at the front end')
Editor found that there are many students do not know when to use Vue.set, in fact, only when you want to assign the attribute has not been defined when you need to use Vue,set, other times generally will not need to use.
4. Use $forceUpdate
I think the existence of $forceUpdate makes many front-end developers no longer pay attention to the principle of two-way data binding, because whenever, after I modify data, calling $forceUpdate will make the Vue component render again, and bug will not exist. But in fact, this method is not recommended because it can cause a lot of unnecessary performance consumption.
A specific way for an array
In fact, it is not only objects, but also arrays that do not respond after data modification, such as the following code
{{item}} modify the name export default {data () {return {list: ['Zhang San','Li Si']}}, methods: {/ / modify the user name handleChangeName () {this.list [0] = 'Wang Wu'}
The above code wants to change the name of Zhang San to Wang Wu. In fact, this change does not take effect because Vue cannot detect the following changing array:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
When you use the index to set an item directly, for example: this.list [index] = newValue
Modify the length property of the array, for example: this.list.length = 0
So in the above example, the data response cannot be triggered by this.list [0] = 'Wang Wu', so what should I do? Vue.set and $forceUpdate mentioned above can solve this problem, for example, Vue.set can write
Vue.set (this.list,0,' Wang Wu') copy the code
In addition to those methods, Vue also provides mutation methods for arrays
When manipulating an array, we usually use many methods provided by the data, such as push,pop,splice and so on. Calling these methods provided above to modify the value of the array in Vue can trigger the data response. For example, the data response can be triggered by changing the above code to the following code
This.list.splice (0Jing 1 Jing 'Wang Wu')
In fact, if Vue relies solely on getter and setter, it is impossible to trigger a data response when an array calls methods such as push,pop, so Vue actually hijacks these methods and wrappers them to mutate.
Vue's wrapper variation on the following methods of the array:
Push
Pop
Shift
Unshift
Splice
Sort
Reverse
So when manipulating the array, calling the above methods can ensure that the data can respond normally. Here is the code that wraps the array method in the Vue source code:
Var original = arrayProto [method]; def (arrayMethods, method, function mutator () {/ / convert arguments to array var args = [], len = arguments.length; while (len--) args [len] = arguments [len]; var result = original.apply (this, args); / / the usage here is the same as dependArray (value), just to get dep var ob = this.__ob__; var inserted Switch (method) {case 'push': case' unshift': inserted = args; break case 'splice': inserted = args.slice (2); break} / / if there is a new data insert, the inserted data should also be a responsive if (inserted) {ob.observeArray (inserted) } / / Notification depends on updating ob.dep.notify (); return result})
Text formatting, filter is simpler
Use filter to simplify logic
What if I want to display the timestamp in yyyy-MM-DD HH:mm:ss format? Do you need to format the date in the code before rendering to the template? Just like down there.
{{dateStr}} {{item.date}} import {format} from'@ / utils/date' export default {data () {return {date: Date.now (), list: [{date: Date.now ()}]}} Computed: {dateStr () {return format (this.date, 'yyyy-MM-DD HH:mm:ss')}, getList () {return this.list.map (item = > {return {... item, date: format (item.date) 'yyyy-MM-DD HH:mm:ss')}})}
As written above, you need to call format for each date field, and then convert it by calculating properties? At this point, you can consider using filter provided by Vue to simplify
{{dateStr | formatDate}} {{item.date | formatDate}} import {format} from'@ / utils/date' export default {filters: {formatDate (value) {return format (value, 'yyyy-MM-DD HH:mm:ss')}}, data () {return {date: Date.now () List: [{date: Date.now ()}]}
Isn't it much easier to modify the above?
Register the global filter
Some filters are used frequently, such as the date filter mentioned above, which is used in many places. At this time, if you define it in every component to be used, it will be a bit redundant. At this time, you can consider Vue.filter registering the global filter.
For global filters, it is generally recommended to add the filters directory to the project, and then add it to the filters directory
/ / filters\ index.js import Vue from 'vue' import {format} from' @ / utils/date' Vue.filter ('formatDate', value = > {return format (value,' yyyy-MM-DD HH:mm:ss')})
Then introduce the files in filters into main.js, which can be used directly in the component. For example, the previous code can be modified to
{{dateStr | formatDate}} {{item.date | formatDate}} export default {data () {return {date: Date.now (), list: [{date: Date.now ()}]}
Isn't it easier?
Developed a plug-in library to install it.
When using some UI frameworks, you often need to use Vue.use to install, such as when using element-ui, it is often written as follows:
Import Vue from 'vue'; import ElementUI from' element-ui'; import 'element-ui/lib/theme-chalk/index.css'; Vue.use (ElementUI, {size:' small'})
After using Vue.use, element-ui can be used directly in the component, which is amazing (Bah, sissy). Next we implement a simplified version of element to see how to install it.
Understand the use of Vue.use
Vue.use is a global method, which needs to be done before you call new Vue () to start the application. The parameters of Vue.use are as follows
/ * plugin: plug-ins to be installed, such as ElementUI * options: configuration information of plug-ins such as {size: 'small'} * / Vue.use (plugin, options)
Simulate the installation logic of element-ui
Think about what element-ui offers we can use after using Vue.use (ElementUI, {size: 'small'})
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
You can use element-ui components directly in the components, and there is no need to import
You can use the v-loading instruction directly
Display loading in the component through this.$loading
Others.
/ / this is a button component import Button from'@ / components/button' / / loading instruction import loadingDirective from'@ / components/loading/directive' / / loading method import loadingMethod from'@ / components/loading' export default {/ * Vue.use requires the plug-in to provide an install method * @ param {*} Vue Vue * @ param {*} plugin configuration information * / install (Vue Options) {console.log (options) / / register components through Vue.components Vue.components (Button.name, Button) / / register global directive Vue.directive ('loading', loadingDirective) / / mount loadingMethod to the Vue prototype chain It is convenient to call Vue.prototype.$loading = loadingMethod}}
With the above code, you have implemented a new version of the element-ui plug-in, so you can install the plug-in through Vue.use in main.js. You may wonder why I use this way of writing. I can still function without this way of writing. The editor thinks that this way of writing has two advantages.
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Standardization, by providing a unified development model, there is a specification to follow for both plug-in developers and users.
Plug-in cache, Vue.use will cache the plug-in when installing the plug-in, that is, if a plug-in is installed multiple times, it will only take effect the first time it is installed.
Application scenarios of plug-ins
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Add a global method or property.
Add global resources: directives / filters / transitions, etc.
Add some component options through global blending.
Add Vue instance methods by adding them to the Vue.prototype.
A library that provides its own API and one or more of the functions mentioned above. Such as element-ui
To improve the performance of Vue rendering, learn about Object.freeze
When a Vue instance is created, it adds all the property in the data object to Vue's responsive system. When the values of these property change, the view will produce a "response", that is, the match will be updated to the new value. But this process actually consumes performance, so for interfaces that have a lot of data but are only displayed, it is not necessary to add property to the responsive system, which can improve rendering performance. How to do it, you need to know about Object.freeze.
On the Vue website, there is a passage: the only exception here is the use of Object.freeze (), which prevents the modification of the existing property and means that the response system can no longer track _ changes. What this means is that if our data uses Object.freeze, we can get the data out of the responsive system, so what should we do?
For example, in the following table, because we are only rendering data, we can optimize performance through Object.freeze.
Export default {data () {const data = Array (1000) .fill (1) .map ((item, index) = > {return {date: '2020-07-11, name: `Zijun ${index} ` Address: 'Greater Xi'an'}) return {/ / here we use Object.freeze tableData: Object.freeze (data)}}
Some students may have questions, if the data in my table is scrolling loaded, won't I be able to add data to tableData if you write like this? Yes, there is no way to add data, but there is a way to solve it, such as the following
Export default {data () {return {tableData: []}}, created () {setInterval (()) = > {const data = Array (1000) .fill (1) .map ((item, index) = > {/ / although the entire array cannot be frozen But you can freeze each data return Object.freeze ({date: '2020-07-11, name: `Zijun ${index} `, address:' Greater Xi'an')}) thisthis.tableData = this.tableData.concat (data)} 2000)} these are all the contents of the article "what are the tips for using Vue?" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
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.