<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>computed</title>
<script src="./vue.js"></script>
</head>
<body>
<div id="app">
<div>methods:{{mTime()}}</div>
<div>computed:{{cTime}}</div>
<div @click="print">打印</div>
</div>
<div id="app2"></div>
<script>
//methods 方法每次调用执行
//computed 依赖缓存 只有computed 中依赖的属性发生改变 才重新计算 rand 改变 cTime() 重新计算
//computed get , set ... 通过 App.cTime = "ok" 触发 computed set 方法
//computed 还可以依赖其它实例的属性... 如 app2的属性
const app2 = new Vue({
el:"#app2",
data(){
return {
rand:0,
}
}
});
let App = new Vue({
el: '#app',
data() {
return {
rand: 0,
}
},
methods: {
mTime() {
return new Date()
}, print() {
// this.rand = Math.random();
//依赖app2.rand
app2.rand = Math.random();
console.log("methods", this.mTime());
console.log("computed", this.cTime);
}
},
computed: {
cTime: {
get() {
// this.rand;
app2.rand;
return new Date();
},
set(val) {
console.log("computed-set", val);
},
}
}
});
App.cTime = "setVal";
</script>
</body>
</html>
《Vue.js实战》第三章 计算属性 computed
最新推荐文章于 2024-06-05 20:43:04 发布

912

被折叠的 条评论
为什么被折叠?



