<
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
>
添加属性
</
title
>
<!--
引入vue.js
-->
<
script
src
="node_modules/vue/dist/vue.js"
></
script
>
<
script
>
window.onload
=
function
(){
new
Vue({
el:
'
#app
'
,
//
2.0不允许挂载到html,body元素上
data:{
info:{id:
1
,price:
15
,name:
"
套餐A
"
}
methods:{
add:
function
(){
//
给info对象添加msg属性并赋值
this
.info.msg
=
"
hello
"
;
</
script
>
</
head
>
<
div
id
="app"
>
{{info.msg}}
<
button
@click
="add"
>
添加
</
button
>
</
div
>
</
body
>
</
html
>
先看看点击按钮之前的效果:
从截图中可以看出这时info对象只有三个属性,点击“添加”按钮刷新,然后在看看info对象的属性,截图如下:
可以看出这时info对象增加了msg属性,但是界面上面没有显示出来msg属性的值。即:
如果在实例创建之后添加新的属性到实例上,不会触发视图更新。
这时就需要使用$set了。代码示例如下:
<!DOCTYPE html>
<html lang="en">
<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>添加属性</title>
<!--引入vue.js-->
<script src="node_modules/vue/dist/vue.js" ></script>
<script>
window.onload=function(){
new Vue({
el:'#app',// 2.0不允许挂载到html,body元素上
data:{
info:{id:1,price:15,name:"套餐A"}
methods:{
add:function(){
// 给info对象添加msg属性并赋值
//this.info.msg="hello";
this.$set(this.info,"msg","hello");
</script>
</head>
<div id="app">
{{info.msg}}
<button @click="add">添加</button>
</div>
</body>
</html>
可以看出:使用了$set之后视图会被更新。
注意:如果是修改对象里面已经存在的属性,则直接修改即可
代码示例如下:
<!DOCTYPE html>
<html lang="en">
<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>添加属性</title>
<!--引入vue.js-->
<script src="node_modules/vue/dist/vue.js" ></script>
<script>
window.onload=function(){
new Vue({
el:'#app',// 2.0不允许挂载到html,body元素上
data:{
info:{id:1,price:15,name:"套餐A"}
methods:{
add:function(){
// 给info对象添加msg属性并赋值
//this.info.msg="hello";
this.$set(this.info,"msg","hello");
modify:function(){
this.info.name="套餐B";
</script>
</head>
<div id="app">
{{info.msg}}
name值:{{info.name}}
<button @click="add">添加</button>
<button @click="modify">修改</button>
</div>
</body>
</html>
二、$delete删除对象属性
可以使用$delete删除对象里面的属性,代码示例如下:
<!DOCTYPE html>
<html lang="en">
<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>添加属性</title>
<!--引入vue.js-->
<script src="node_modules/vue/dist/vue.js" ></script>
<script>
window.onload=function(){
new Vue({
el:'#app',// 2.0不允许挂载到html,body元素上
data:{
info:{id:1,price:15,name:"套餐A"}
methods:{
add:function(){
// 给info对象添加msg属性并赋值
//this.info.msg="hello";
this.$set(this.info,"msg","hello");
modify:function(){
this.info.name="套餐B";
del:function(){
// 删除info对象里面的price属性
this.$delete(this.info,"price");
</script>
</head>
<div id="app">
{{info.msg}}
name值:{{info.name}}
<button @click="add">添加</button>
<button @click="modify">修改</button>
<button @click="del">删除</button>
</div>
</body>
</html>