1.是否加括号。method是方法,在插值语法{{}}中fullName作为一个返回值所以必须为{{fullName()}},而computed作为计算属性不用加
(ps:在事件绑定中()加不加都可以,想传参数时可以加但是加了事件对象event就没有了,除非使用$event去占位)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../js/vue.js"></script>
</head>
<body>
<div id="root">
姓:<input type="text" v-model="firstName"><br>
名:<input type="text" v-model="lastName"><br>
全名:<span>{{fullName()}}</span>
</div>
</body>
<script>
new Vue({
el: '#root',
data: {
firstName: '小猪',
lastName: '佩奇'
},
methods: {
fullName() {
return this.firstName + '-' + this.lastName
}
}
})
</script>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../js/vue.js"></script>
</head>
<body>
<div id="root">
姓:<input type="text" v-model="firstName"><br>
名:<input type="text" v-model="lastName"><br>
全名:<span>{{fullName}}</span>
</div>
</body>
<script>
const vm = new Vue({
el: '#root',
data: {
firstName: '小猪',
lastName: '佩奇',
x: '2'
},
computed: {
fullName: {
get() {
//get有什么作用?当有人读取fullName时,get就会被调用,且返回值就作为fullName的值
//get什么时候调用?1.初次读取fullName时。2.所依赖的数据发生变化时。
console.log('get被调用');//get只有一次,其余为缓存
return this.firstName + '-' + this.lastName
},
//set什么时候调用?1.fullName被修改时。2.所依赖的数据发生变化时。
set(value) {
console.log('set', value);
const arr = value.split('-')
this.firstName = arr[0]
this.lastName = arr[1]
}
}
}
})
</script>
</html>
2.是否存有缓存。methods没有缓存,调用相同的值计算还是会重新计算。competed有缓存,在值不变的情况下不会再次计算,只有当关联属性发生变化时,才会重新调用。