Home > Web Front-end > JS Tutorial > Analysis of listener use cases in Vue.js

Analysis of listener use cases in Vue.js

php中世界最好的语言
Release: 2018-06-01 11:48:11
Original
1642 people have browsed it

This time I will bring you an analysis of the use case of the listener in Vue.js. What are the precautions when using the listener in Vue.js. The following is a practical case, let's take a look.

Vue listener watch

While computed properties are more appropriate in most cases, sometimes a custom listener is needed. device. This is why Vue provides a more general way to respond to changes in data through the watch option. This approach is most useful when you need to perform asynchronous or expensive operations when data changes. For example:

<p id="watch-example">
<p>
Ask a yes/no question:
<input v-model="question">
</p>
<p>{{ answer }}</p>
</p>
Copy after login
<!-- 因为 AJAX 库和通用工具的生态已经相当丰富,Vue 核心代码没有重复 -->
<!-- 提供这些功能以保持精简。这也可以让你自由选择自己更熟悉的工具。 -->
<script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.13.1/lodash.min.js"></script>
<script>
var watchExampleVM = new Vue({
el: '#watch-example',
data: {
question: '',
answer: 'I cannot give you an answer until you ask a question!'
},
watch: {
// 如果 `question` 发生改变,这个函数就会运行
question: function (newQuestion, oldQuestion) {
this.answer = 'Waiting for you to stop typing...'
this.getAnswer()
}
},
methods: {
// `_.debounce` 是一个通过 Lodash 限制操作频率的函数。
// 在这个例子中,我们希望限制访问 yesno.wtf/api 的频率
// AJAX 请求直到用户输入完毕才会发出。想要了解更多关于
// `_.debounce` 函数 (及其近亲 `_.throttle`) 的知识,
// 请参考:https://lodash.com/docs#debounce
getAnswer: _.debounce(
function () {
if (this.question.indexOf('?') === -1) {
this.answer = 'Questions usually contain a question mark. ;-)'
return
}
this.answer = 'Thinking...'
var vm = this // this重定向
axios.get('https://yesno.wtf/api')
.then(function (response) {
vm.answer = _.capitalize(response.data.answer)
})
.catch(function (error) {
vm.answer = 'Error! Could not reach the API. ' + error
})
},
// 这是我们为判定用户停止输入等待的毫秒数
500
)
}
})
</script>
Copy after login

Advanced usage of listener (watch)

Assume that there is the following code:

<p>
  <p>FullName: {{fullName}}</p>
  <p>FirstName: <input type="text" v-model="firstName"></p>
</p>
new Vue({
 el: '#root',
 data: {
 firstName: 'Dawei',
 lastName: 'Lou',
 fullName: ''
 },
 watch: {
 firstName(newName, oldName) {
  this.fullName = newName + ' ' + this.lastName;
 }
 } 
})
Copy after login

The above The effect of the code is that when we enter firstName, wacth monitors the new value of each modification and then calculates and outputs fullName.

handler method and immediate attribute

One feature of the watch here is that it will not be executed when it is initially bound. It must wait until firstName Monitoring calculations are only performed when changes occur. So what if we want to execute the change when it is initially bound? We need to modify our watch writing method. The modified watch code is as follows:

watch: {
 firstName: {
 handler(newName, oldName) {
  this.fullName = newName + ' ' + this.lastName;
 },
 // 代表在wacth里声明了firstName这个方法之后立即先去执行handler方法
 immediate: true
 }
}
Copy after login

Have you noticed the handler? We have bound a handler method to firstName. The watch method we wrote before is actually written by default. This handler, Vue.js will handle this logic, and the final compiled version is actually this handler.

And immediate: true means that if firstName is declared in wacth, the handler method inside will be executed immediately. If it is false, the effect will be the same as our previous one, and it will not be executed during binding. implement.

deep attribute

There is also an attribute deep in watch. The default value is false, which represents whether to monitor deeply. For example, there is one in our data obj attribute:

<p>
  <p>obj.a: {{obj.a}}</p>
  <p>obj.a: <input type="text" v-model="obj.a"></p>
</p>
new Vue({
 el: '#root',
 data: {
 obj: {
  a: 123
 }
 },
 watch: {
 obj: {
  handler(newName, oldName) {
   console.log('obj.a changed');
  },
  immediate: true
 }
 } 
})
Copy after login

When we enter the data view in the input box to change the value of obj.a, we find that it is invalid. Due to limitations of modern JavaScript (and the deprecation of Object.observe), Vue cannot detect the addition or removal of object properties. Since Vue performs the getter/setter conversion process on the property when initializing the instance, the property must exist on the data object in order for Vue to convert it so that it is responsive.

By default, the handler only listens for changes in the reference of the obj attribute. It will only listen when we assign a value to obj. For example, we reassign obj in the mounted event hook function:

mounted: {
 this.obj = {
 a: '456'
 }
}
Copy after login

In this way, our handler will be executed and obj.a changed will be printed.

On the contrary, what if we need to monitor the value of attribute a in obj? This is when the deep attribute comes in handy!

watch: {
 obj: {
 handler(newName, oldName) {
  console.log('obj.a changed');
 },
 immediate: true,
 deep: true
 }
}
Copy after login

deep means in-depth observation. The listener will traverse layer by layer and add this listener to all properties of the object. However, the performance overhead will be very large. Any modification of obj Any attribute inside will trigger the handler in this listener.

Optimization, we can use stringform monitoring.

watch: {
 'obj.a': {
 handler(newName, oldName) {
  console.log('obj.a changed');
 },
 immediate: true,
 // deep: true
 }
}
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Using JS to determine the content contained in a string Summary of methods

JS HTML5 real binding mouse event Particle animation

The above is the detailed content of Analysis of listener use cases in Vue.js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template