demand

In the previous section, I implemented a name concatenation case by listening for keyUP events. The Vue framework provides a Watch component that can be used to listen for changes in data and then execute relevant business methods.

In this chapter, watch can be used to achieve this. Let’s take a look at the basic functions of the official website.

Listener watch official website description

While computing properties is more appropriate in most cases, sometimes a custom listener is required. That’s why Vue provides a more generic way to respond to changes in data with the Watch option. This approach is most useful when asynchronous or expensive operations need to be performed when data changes.

Such as:

<div id="watch-example">
  <p>
    Ask a yes/no question:
    <input v-model="question">
  </p>
  <p>{{ answer }}</p>
</div>
<! Because the AJAX library and common tool ecosystem 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://cdn.jsdelivr.net/npm/[email protected]/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: {
    // If 'question' changes, the function is run
    question: function (newQuestion, oldQuestion) {
      this.answer = 'Waiting for you to stop typing... '
      this.debouncedGetAnswer()
    }
  },
  created: function () {
    // '_. Debounce' is a function that limits the frequency of operations through Lodash.
    // In this case, we want to limit the frequency of access to yesNo. WTF/API
    // The AJAX request is not sent until the user has entered. Want to learn more about
    // '_. Debounce' functions (and their relatives' _. Throttle '),
    // Please refer to https://lodash.com/docs#debounce
    this.debouncedGetAnswer = _.debounce(this.getAnswer, 500)},methods: {
    getAnswer: function () {
      if (this.question.indexOf('? ') = = = -1) {
        this.answer = 'Questions usually contain a question mark. ; -) '
        return
      }
      this.answer = 'Thinking... '
      var vm = 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
        })
    }
  }
})
</script>
Copy the code

Results:

Ask a yes/no question:

I cannot give you an answer until you ask a question!

In this example, using the Watch option allows us to perform an asynchronous operation (accessing an API), limit how often we perform that operation, and set the intermediate state until we get the final result. These are all things you can’t do with computed properties.

In addition to the Watch option, you can also use the imperative VM.$watch API.

As can be seen from the above example, simply speaking, watch is to monitor a V-Model parameter. When the monitored parameter changes, the written function method is executed.

Let’s use this in the name concatenation case.

The sample

1. Use Watch to write the name splicing case code

<! DOCTYPEhtml>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>Title</title>
		<! Import vue. Js library -->
		<script src="lib/vue.js"></script>
	</head>
	<body>

		<div id="app">

			<! -- form>(label+input#input$+br)*3 -->
			<form action="">
				<label for="input1">Last name:</label>
				<input type="text" id="input1" v-model="firstname" autocomplete="off">
				<br>
				<label for="input2">Name:</label>
				<input type="text" id="input2" v-model="lastname" autocomplete="off">
				<br>
				<label for="input3">Name:</label>
				<input type="text" id="input3" v-model="fullname">
				<br>
			</form>

		</div>

		<script>
			// 2. Create a Vue instance
			var vm = new Vue({
				el: '#app'.data: {
					firstname: "".lastname: "".fullname: "",},methods: {},
				watch: { // Use this property to monitor changes in the specified data and then trigger the corresponding function handler in the watch
					'firstname': function(newVal, oldVal) {
						// newVal is the new value, oldVal is the old value.

						console.log('Change in firstName monitored');
						console.log(newVal + The '-' + oldVal);
						this.fullname = newVal + this.lastname

					},
					'lastname': function(newVal) {
						console.log(newVal);
						this.fullname = this.firstname + newVal
					}
				}

			});
		</script>

	</body>
</html>
Copy the code

2. Open the browser and view the result

It can be seen from the effect that the use of Watch can realize such data changes and implement relevant business methods.

For more exciting original Devops articles, please come to my official account: Devops Community: