您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>vue修改数组元素方法</title>
</head>
<body>
<div id="root">
<div v-for="item in arr">
{{ item }}
</div>
<button @click="changeArr1">修改数组元素方法--方法一</button>
<button @click="changeArr2">修改数组元素方法--方法二</button>
<button @click="changeArr3">修改数组元素方法--方法三</button>
<button @click="getTheArr">获取数组元素</button>
<button @click="getTheNewArr">获取新数组元素</button>
<button @click="addUserObj">增加/修改对象元素</button>
<button @click="delUserObj">删除对象元素</button>
<button @click="updateUserObj">修改/增加对象元素</button>
<button @click="printUserObj">打印对象元素</button>
<button @click="addUserArr">增加数组元素</button>
<button @click="delUserArr">删除数组元素</button>
<br>//遍历数组:
<div v-for="(v, k, index) in user">
<p>
uid: {{k}},
avatar: {{v.avatar}},
nick: {{v.nick}}
</p>
</div>
<div v-for="item in user">
{{item.nick}}——{{item.avatar}}
</div>
点一次显示一个头像
<div></div>>
</div>
<script src="./vue.js"></script>
<script type="text/javascript">
var vm = new Vue({
el: '#root',
data: {
arr: [1, 2, 3],
user: {
"1": {
"avatar": "xxx.xx/1.png",
"nick": "你爹"
},
"2": {
"avatar": "xxx.xx/2.png",
"nick": "你爷"
},
}
},
methods: {
changeArr1: function() {
Vue.set(vm.arr, 0, '方法一');
},
changeArr2: function() {
vm.$set(vm.arr, 0, '方法二');
},
changeArr3: function() {
this.arr.splice(0, 1, '方法三');
//vm.arr.splice(0,1,'方法三');
},
//获取元素
getTheArr: function() {
console.log(this.arr[0]);
},
//获取元素
getTheNewArr: function() {
console.log(this.user["1"]["avatar"]);
},
//给对象增加元素
addUserObj: function() {
console.log(this.user)
Vue.set(this.user, "3", {"avatar":"xxx.xx/3.png","nick":"阿三"})
console.log(this.user);
console.log(this.user["3"]["avatar"]);
},
//删除对象元素
delUserObj: function() {
//console.log(this.user["1"]["avatar"])
console.log(this.user);
Vue.delete(this.user, "1");
console.log(this.user);
},
updateUserObj: function() {
Vue.set(this.user, "3", {"avatar":"yyy.yy/3.jpg","nick":"三哥"})
},
//给数组添加元素
addUserArr: function() {
this.arr.push("嘿嘿嘿");
console.log(this.arr);
},
//删除数组中元素
delUserArr: function() {
arrLen = this.arr.length;
Vue.delete(this.arr, arrLen - 1);
console.log(this.arr);
},
//在js中遍历vue的data中的内容
printUserObj: function() {
for (let key in this.user) {
console.log(key, this.user[key]["nick"], this.user[key]["avatar"]);
}
}
}
});
</script>
</body>
</html>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。