“This article has participated in the call for good writing activities, click to view: the back end, the big front end double track submission, 20,000 yuan prize pool waiting for you to challenge!”

preface

I believe many students will often use or be asked questions about the concept of one-way data flow and two-way data binding when learning Vue. What is the difference between them? Let’s take a look.

Unidirectional data flow

One-way data flow in Vue is actually: when the data in the Model changes, the value in the View will be one-way modified, and when the value in the View changes, the Model will not sense. The practical application is v-bind one-way data.

Two-way data binding

In contrast to one-way data flow, two-way data binding means that more View changes are notified to the Model layer. That is the concrete implementation of MVVM. Changes in Model and View values are notified to each other via the ViewModel for synchronization. The practical application is V-Model two-way data binding.

code

<! DOCTYPEhtml>
<html>
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
		<title>Unidirectional & bidirectional</title>
	</head>
	<body>
		<div id="app">
			<h1>Unidirectional data flow</h1>{{mytime}}<br>
			<button type="button" @click="shuax">The refresh time</button>
			<br><br>
			<hr >
			<h1>Two-way data binding</h1>
			<input v-model="sxbind"/>
			<br>The data you enter is: {{sxbind}}</div>

		<script type="text/javascript">
			app = new Vue({
				el: '#app'.data: {
					mytime:new Date().toLocaleTimeString(),
					sxbind:' '
				},
				methods: {
					shuax:function(){
						this.mytime = new Date().toLocaleTimeString(); }}})</script>
	</body>
</html>
Copy the code

One-way data flow effect

Bidirectional data binding effect

conclusion

One-way data flow is used to notify changes in the Model layer to the View layer through props. Two-way data binding is implemented through the set() and get() methods of Object.defineProperty(), and when one party changes, the other party is reminded to update the value, thus synchronizing the data changes.

That’s all for today, thank you for reading, and we’ll see you next time.