vue.js $set的使用 数组
2023-09-27 14:28:58 时间
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="vue.js"></script>
<style>
.blue {
color: blue;
}
</style>
</head>
<body>
<div id="example-1">
<ul>
<template v-for="item in items">
<li>
{{$index}}.{{ item.msg }}
<button v-on:click="f5(item)">vm.items.splice(index, 1)</button>
<button v-on:click="f6(item)">vm.remove</button>
</li>
</template>
</ul>
<ul>
<li>
<button v-on:click="f1">vm.items[0] = {} 失效</button>
</li>
<li>
<button v-on:click="f2">vm.items.$set(0, { childMsg: 'Changed!'}) </button>
</li>
<li>
<button v-on:click="f3">vm.items.length = 0 失效</button>
</li>
<li>
<button v-on:click="f4">vm.items={}</button>
</li>
</ul>
<div class="blue">
{{$data | json }}
</div>
<pre>
因为 JavaScript 的限制,Vue.js 不能检测到下面数组变化:
直接用索引设置元素,如 vm.items[0] = {};
修改数据的长度,如 vm.items.length = 0。
</pre>
</div>
<script>
var vm = new Vue({
el: '#example-1',
data: {
items: [{
msg: 'Foo'
}, {
msg: 'Bar'
}, {
msg: 'George'
}]
},
methods: {
f1: function() {
vm.items[0] = {}; // 失效
},
f2: function() {
vm.items.$set(0, {
childMsg: 'Changed!'
})
vm.items.$set(2, {
msg: 'dongtao!'
})
},
f3: function() {
vm.items.length = 0; // 失效
},
f4: function() {
vm.items = {}
},
f5: function(item) {
var index = this.items.indexOf(item) //Search an array for the item
if (index !== -1) {
this.items.splice(index, 1) //Selects a part of an array, and returns the new array
}
},
f6: function(item) {
this.items.$remove(item)
}
}
})
</script>
</body>
</html>
相关文章
- vue路由跳转的方式
- vue.js帐号,密码,邮箱和移动手机号码正则验证
- 精品微信小程序鲜花销售系统购物商城+后台|前后分离VUE
- Vue.js Ajax(axios)
- VS Code导入已存在的Vue.js工程
- vue X 周末看看 霸个位
- Vue 拦截器的使用
- Vue技术6.3Vue中的数据代理
- Vue.js 笔记之 img src
- 适合编程初学者的开源项目:小游戏2048(Vue版)
- 从 vue.js 源码角度再看数据绑定
- Vue 服务端渲染(SSR)、Nuxt.js - 从入门到实践
- 使用Vue.js和Laravel构建的开源博客。
- Vue.js 实用技巧(二)
- Vue.js 系列教程 5:动画
- 史上最详细的 webpack 讲解 1 (vue-cli 中 build.js)
- 基于Vue.js的表格分页组件
- vue.js 由浅至深学习宝典
- 一步一步教你用 Vue.js + Vuex 制作专门收藏微信公众号的 app