Value transfer of components in vue

Pass value from parent component to child component

This is the first code:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Hello World</title>
	<script src="vue.js" type="text/javascript" charset="utf-8"></script>
	<script src="jquery-3.3.1.min.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
	<div id="app">
		<input type="" name="" v-model="inputvalue">
		<button type="" v-on:click="handleItemSubmit">Submission</button>
		<ul>
			<todo-item  v-for="item in list"
						v-bind:content="item">
			</todo-item>
		</ul>
	</div>
	<script>
		var TodoItem = {
			props : ["content"],
			template : "<li>{{content}}</li>"
		}
		var app = new Vue({
			el : "#app",
			data : {
				list : [],
				inputvalue : ""
			},
			components : {
				TodoItem : TodoItem
			},
			methods : {
				handleItemSubmit : function () {
					this.list.push(this.inputvalue);
					this.inputvalue = "";
				}
			}
		});
	</script>
</body>
</html>

The data of data in the parent component is passed to the child component through v-for and v-bind

Now the child component passes the value to the parent component

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Hello World</title>
	<script src="vue.js" type="text/javascript" charset="utf-8"></script>
	<script src="jquery-3.3.1.min.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
	<div id="app">
		<input type="" name="" v-model="inputvalue">
		<button type="" v-on:click="handleItemSubmit">Submission</button>
		<ul>
			<todo-item  v-for="(item, index) in list"
						v-bind:content="item"
						v-bind:index="index"
						v-on:delete="handleItemDelete">
			</todo-item>
		</ul>
	</div>
	<script>
		var TodoItem = {
			props : ["content", "index"],
			template : "<li v-on:click='handleItemClick'>{{content}}</li>",
			methods : {
				handleItemClick : function () {
					this.$emit("delete", this.index);
				}
			}
		}
		var app = new Vue({
			el : "#app",
			data : {
				list : [],
				inputvalue : ""
			},
			components : {
				TodoItem : TodoItem
			},
			methods : {
				handleItemSubmit : function () {
					this.list.push(this.inputvalue);
					this.inputvalue = "";
				},
				handleItemDelete : function (index) {
					this.list.splice(index, 1);
				}
			}
		});
	</script>
</body>
</html>

To pass values to the parent component, first add a handleItemClick function in the child component template template, then add handleItemClick function in the methods of the child component object, call this.$emit("delete", this.index), which is used to listen to the function number of the parent component before and the value passed to the parent component function after

Keywords: Vue Javascript JQuery

Added by Hellomonkey on Wed, 01 Jan 2020 17:53:46 +0200