Vue3 computes attributes
Computed attribute keyword: computed.
Computed properties are useful when dealing with some complex logic.
Take a look at the following example of reversing strings:
<! DOCTYPE HTML > < HTML > <head> <meta charset=" UTF-8 "> <title>Vue test instance </title> <script src="https://unpkg.com/vue@next"></script> </head> <body> <div id="app"> {{ message.split('').reverse().join('') }} </div> <script> const app = { data() { return { message: 'BAIDU!! ' } } } Vue.createApp(app).mount('#app') </script> </body> </html>Copy the code
The template in the above code becomes relatively complex and difficult to understand.
Let’s look at an example using computed attributes:
<! DOCTYPE HTML > < HTML > <head> <meta charset=" UTF-8 "> <title>Vue test instance </title> <script SRC = "https://unpkg.com/vue@next" > < / script > < / head > < body > < div id = "app" > < p > the original string: {{message}} < / p > < p > after calculating reverse string: {{ reversedMessage }}</p> </div> <script> const app = { data() { return { message: 'BAIDU!! '}}, computed: {// Calculate the getter reversedMessage for attributes: Return this.message.split('').reverse().join('')}}} vue.createApp (app).mount('#app') </script> </body> </html>Copy the code
A calculated property reversedMessage is declared in the above code.
The provided function will be used as the getter for the attribute VM. reversedMessage.
Vm. reversedMessage depends on VM. message and is updated when the VM. message changes.
computed vs methods
Instead of computed, we can use methods. The effect is the same, but computed is based on its dependency cache, which is reevaluated only when the dependency changes. With methods, functions are always called again when rendering again.
<! DOCTYPE HTML > < HTML > <head> <meta charset=" UTF-8 "> <title>Vue test instance </title> <script SRC = "https://unpkg.com/vue@next" > < / script > < / head > < body > < div id = "app" > < p > the original string: {{message}}</p> <p> Reverse strings using computed data: {{reversedMessage}}</p> <p> Reverse strings using methods: {{ reversedMessage2() }}</p> </div> <script> const app = { data() { return { message: 'BAIDU!! '}}, computed: {// Calculate the getter reversedMessage for attributes: Function () {return this.message.split('').reverse().join('')}}, methods: {reversedMessage2: function () { return this.message.split('').reverse().join('') } } } Vue.createApp(app).mount('#app') </script> </body> </html>Copy the code
Arguably, using computed performance is better, but if you don’t want caching, you can use the Methods attribute.
computed setter
Computed attributes only have getters by default, but you can provide a setter if you want:
<! DOCTYPE HTML > < HTML > <head> <meta charset=" UTF-8 "> <title>Vue test instance </title> <script src="https://unpkg.com/vue@next"></script> </head> <body> <div id="app"> </div> <script> const app = { data() { return { name: 'Google', url: 'http://www.google.com' } }, computed: { site: { // getter get: function () { return this.name + ' ' + this.url }, // setter set: function (newValue) { var names = newValue.split(' ') this.name = names[0] this.url = names[names.length - 1] } } } } vm = Vue.createApp(app).mount('#app') document.write('name: ' + vm.name); document.write('<br>'); document.write('url: ' + vm.url); Document. write('<br>------ update data ------<br>'); // call setter, vm.name and vm.url will be updated accordingly vm.site = 'baidu https://www.baidu.com'; document.write('name: ' + vm.name); document.write('<br>'); document.write('url: ' + vm.url); </script> </body> </html>Copy the code
Site = ‘baidu www.baidu.com’
Setter will be called, vm.name and vm.url will be updated accordingly.
Vue3 listens for properties
In this module, we introduce Vue3 listening attribute Watch, through which we can respond to data changes.
The following example implements a counter using watch:
<! DOCTYPE HTML > < HTML > <head> <meta charset=" UTF-8 "> <title>Vue test instance </title> <script src="https://unpkg.com/vue@next"></script> </head> <body> <div id = "app"> <p style = "font-size:25px;" < p> < button@click = "counter++" style = "font-size:25px; </button> </div> <script> const app = {data() {return {counter: 1 } } } vm = Vue.createApp(app).mount('#app') vm.$watch('counter', function(nval, Oval) {alert(' counter value change :' + oval + 'becomes' + nval + '! '); }); </script> </body> </html>Copy the code
The following example is used to convert kilometers to meters:
<! DOCTYPE HTML > < HTML > <head> <meta charset=" UTF-8 "> <title>Vue test instance </title> <script SRC = "https://unpkg.com/vue@next" > < / script > < / head > < body > < div id = "app" > k: < div style = "box-sizing: border-box! Important; word-wrap: break-word! Important;" <input type = "text" v-model = "meters"> </div> <p id="info"></p> <script> const app = { data() { return { kilometers : 0, meters:0 } }, watch : { kilometers:function(val) { this.kilometers = val; this.meters = this.kilometers * 1000 }, meters : function (val) { this.kilometers = val/ 1000; this.meters = val; } } } vm = Vue.createApp(app).mount('#app') vm.$watch('kilometers', function (newValue, {// This callback will call document.getelementById ("info"). InnerHTML = "+ oldValue +" " + newValue; }) </script> </body> </html>Copy the code
In this code, we create two input fields. In the data property, kilometers and meters both start with 0. The Watch object creates two monitoring methods for the data object: Kilometers and meters. When we reenter data in the input box, the Watch will listen for data changes in real time and change its value.
Watch is used in asynchronous loading
Loading asynchronous data Vue provides a more generic way to respond to data changes through the Watch option.
The following example uses the Axios library, which you’ll learn about later. It’s fun to copy and run:
<! DOCTYPE HTML > < HTML > <head> <meta charset=" UTF-8 "> <title>Vue test instance </title> <! Because the ecosystem of AJAX libraries and common tools is already quite rich, the Vue core code is not duplicated --> <! Provide these features to keep things lean. This also gives you the freedom to choose the tools you're more familiar with. -- > < script SRC = "https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js" > < / script > < script SRC ="https://unpkg.com/vue@next"></script> </head> <body> <div id="watch-example"> <p> Enter a question, ending with a? Sign to output the answer: <input v-model="question" /> </p> <p>{{ answer }}</p> </div> <script> const watchExampleVM = Vue.createApp({ data() { Return {question: ", answer: 'Each question ends with a? Number. '}}, watch: {// Whenever the problem changes, this function will run to? Question (newQuestion, oldQuestion) {if (newquestion.indexof ('? ') > -1) {this.getAnswer()}}, methods: {getAnswer() {this.answer = 'loading... ' axios .get('https://yesno.wtf/api') .then(response => { this.answer = response.data.answer }) .catch(error => { This.answer = 'Error! Unable to access the API. ' + error }) } } }).mount('#watch-example') </script> </body> </html>Copy the code
End of today’s share of love ——————–