Vue - 实现简单类数据存储效果(操作数组)

 

Vue - 实现简单类数据存储效果(操作数组)

方式一 、使用vue实例进行数据传输实现

<!DOCTYPE html>
<html lang="zh">
<head>
	<meta charset="UTF-8">
	<title>todoList案例</title>
</head>
<body>
	<div id="app">
		<div>
			<input type="text" v-model="val">
			<button type="button" @click="submitMsg">提交</button>
		</div>
		<ul>
			<li v-for="(v, i) in list" :key="i" @click="removeMsg(i)">第{{ i + 1 }}条:{{ v }}</li>
		</ul>
		{{ list }}
	</div>
</body>
<script src="js/vue-2.5.17.js"></script>
<script type="text/javascript">
	new Vue({
		el: "#app",
		data: {
			val: "",
			list: []
		},
		methods: {
			submitMsg () {
			// push、splice是js的数组操作的常用方法
				// 往list中添加input框中的value
				if (this.val) {
					this.list.push(this.val);
					this.val = ""
				}
			},
			removeMsg(index) {
				this.list.splice(index, 1)
			}
		}
	})
</script>
</html>

方式二、使用父子组件进行数据的传输实现

(提交数据,获取父组件内的值使用父传子;实现删除数据,使用子传父)

<!DOCTYPE html>
<html lang="zh">
<head>
	<meta charset="UTF-8">
	<title>todoList案例</title>
</head>
<body>
	<div id="app">
		<div>
			<input type="text" v-model="val">
			<button type="button" @click="submitMsg">提交</button>
		</div>
		<ul>
			<!-- <li v-for="(v, i) in list" :key="i" @click="removeMsg(i)">{{ v }}</li> -->
			<todo-list v-for="(v, i) in list" :key="i" :v0="v" :i0="i" @delect_action="delect_action"></todo-list>
		</ul>
	</div>
</body>
<script src="js/vue-2.5.17.js"></script>
<script type="text/javascript">
	Vue.component("todo-list", {
		template: "<li @click='delect_action'><span>第{{ i0 + 1 }}条: </span><span>{{ v0 }}</span></li>",
		props: ['v0', 'i0'],
		methods: {
			delect_action () {
				this.$emit("delect_action", this.i0)
			}
		}
	})
	

	new Vue({
		el: "#app",
		data: {
			val: "",
			list: []
		},
		methods: {
			submitMsg () {
				// 往list中添加input框中的value
				if (this.val) {
					this.list.push(this.val);
					this.val = ""
				}
			},
			delect_action(index) {
				this.list.splice(index, 1)
			}
		}
	})
</script>
</html>