这里我定义了一个列表数据,我将通过三个不同的按钮来控制列表数据。
首先在列表中动态新增一条数据:
html>
<html>
<head>
<meta name="description" content="this.$Set() 演示" />
<meta charset="utf-8">
<title>JS Bintitle>
<link rel="stylesheet" href="http://unpkg.com/element-ui@2.4.11/lib/theme-chalk/index.css">
<script src="//unpkg.com/vue/dist/vue.js">script>
<script src="//unpkg.com/element-ui@2.4.11/lib/index.js">script>
head>
<body>
<div id="app2">
<p v-for="item in items" :key="item.id">
{{item.message}}
p>
<button class="btn" @click="btn1Click()">点我试试button><br/>
div>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
<script>
var vm2=new Vue({
el:“#app2”,
data:{
items:[
{message:“Test one”,id:“1”},
{message:“Test two”,id:“2”},
{message:“Test three”,id:“3”}
]
},
methods:{
btn1Click:function(){
this.items.push({message:“动态新增”});
}
}
});
script>
body>
html>
复制代码
点击之后列表新增了一条数据:
通过数组的变异方法(Vue数组变异方法)我们可以动态控制数据的增减,但是我们却无法做到对某一条数据的修改。这时候就需要Vue的内置方法来帮忙了~
此时我们需要知道Vue.set()需要哪些参数,官方API:Vue.set()
调用方法:Vue.set( target, key, value )
target:要更改的数据源(可以是对象或者数组)
key:要更改的具体数据
value :重新赋的值
我们依然用上面列表举例:
html>
<html>
<head>
<meta name="description" content="this.$Set() 演示" />
<meta charset="utf-8">
<title>JS Bintitle>
<link rel="stylesheet" href="http://unpkg.com/element-ui@2.4.11/lib/theme-chalk/index.css">
<script src="//unpkg.com/vue/dist/vue.js">script>
<script src="//unpkg.com/element-ui@2.4.11/lib/index.js">script>
head>
<body>
<div id="app2">
<p v-for="item in items" :key="item.id">
{{item.message}}
p>
<button class="btn" @click="btn2Click()">使用this.$set 动态赋值button><br/><br/>
<button class="btn" @click="btn3Click()">为data中的items列表 push新增属性button>
div>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
<script src=“…/…/dist/vue.min.js”>script>
<script>
var vm2=new Vue({
el:“#app2”,
data:{
items:[
{message:“Test one”,id:“1”},
{message:“Test two”,id:“2”},
{message:“Test three”,id:“3”}
]
},
methods:{
btn2Click:function(){
Vue.set(this.items,0,{message:“Change Test”,id:‘10’})
},
btn3Click:function(){
var itemLen=this.items.length;
Vue.set(this.items,itemLen,{message:“Test add attr”,id:itemLen});
}
}
});
script>
body>
html>
复制代码
我点击第一个按钮后运行methods中的btn2Clcick方法,此时我要将Test one更改为Change Test
运行后的结果:此时列表中第一列的Test one已经变成了Change Test
这里得警惕一种情况: 当写惯了JS之后,有可能我会想改数组中某个下标的中的数据我直接**this.items[XX]**就改了,如:
btn2Click:function(){
this.items[0]={message:"Change Test",id:'10'}
}
复制代码
这种情况,是Vue文档中明确指出的注意事项,由于 JavaScript 的限制,Vue 不能检测出数据的改变,所以当我们需要动态改变数据的时候,Vue.set()完全可以满足我们的需求。
仔细看的同学会问了,这不是还有一个按钮吗,有什么用?
我们还是直接看: