vue计算属性
计算属性简单使用
<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="./vue3.js"></script>
</head>
<body>
<div id="app">
<!--
计算属性computed
对于任何包含响应式数据的复杂逻辑,应使用计算属性
-->
<h2>{{ getlist()}}</h2>
<h2>{{ getlist()}}</h2>
<h2>{{ getlist()}}</h2>
<h2>{{fullname}}</h2>
<h2>{{fullname}}</h2>
<h2>{{fullname}}</h2>
<button @click="omlint">修改last</button>
</div>
<script>
const app = Vue.createApp({
data() {
return {
firstName:"qw",
lastNmae:"qa"
}
},
methods: {
getlist(){
console.log("第一");
console.log("第二");
return this.firstName+""+this.lastNmae
},
//修改属性值的操作
omlint(){
this.lastNmae='add'
}
},
computed: {
// 计算属性对应的默认是一个函数
// 多次调用计算属性,只执行一次,是因为计算属性会基于他们的依赖关系进行缓存
// 数据不发生变化时,计算属性不需要重新计算
// 反之计算属性变了,在使用时计算属性会重新进行计算
fullname(){
// return "hello world"
console.log('get+++++');
return this.firstName+""+this.lastNmae
}
},
}).mount("#app")
</script>
</body>
</html>
get,set
<body>
<div id="app">
<h2>{{fullname}}</h2>
<button @click="setFullname">点击</button>
</div>
<script>
const app = Vue.createApp({
data() {
return {
firstName:"qw",
lastNmae:"qa"
}
},
methods: {
setFullname(){
this.fullname="abc"
}
},
computed:{
fullname:{
get:function(){
return this.firstName+""+this.lastNmae
},
set:function(value){
const names=value.split("")
this.firstName=names[0]
this.lastNmae=names[1]
}
}
}
深度监听
<body>
<div id="app">
<h2>{{info.name}}</h2>
<button @click="amend">修改</button>
</div>
<script>
const app = Vue.createApp({
data() {
return {
info:{name:"wa",age:12}
}
},
methods: {
amend(){
this.info.name='aaa'
}
},
watch:{
//默认的watch监听不会进行深度监听
// info(newValue,oldValue){
// console.log("侦听到info的改变",newValue,oldValue);
// }
info:{
handler(newValue,oldValue){
console.log(`侦听到info改变`,newValue,oldValue);
console.log(newValue==oldValue);
},
deep:true
}
}
}).mount("#app")
</script>
侦听器
<body>
<div id="app">
<!--
侦听器: 开发中,在data返回的对象中定义的对象数据通过插值等方式绑定的template中
当数据发生变化自动更新来显示最新数据
但在某些情况下希望监听某个数据的变化,这时就可以用watch
-->
<h2>{{counter}}</h2>
<button @click="changcouer">点击</button>
</div>
<script>
const app = Vue.createApp({
data() {
return {
counter:"hello word",
info:{name:"wz",age:12}
}
},
methods: {
changcouer(){
this.counter='你好',
this.info={name:"kebi",age:12}
}
},
watch:{
//有默认2个参数 newValue可以拿到新的值,oldValue可以拿到旧的值
counter(newValue,oldValue){
console.log('数据发生了变化',newValue,oldValue);
},
info(newValue,oldValue){
// 对象拿到的是一个代理
console.log("info发生改变",newValue,oldValue);
//可获取原生对象但是不是原对象
console.log({...newValue});
// 获取原生对象
console.log(Vue.toRaw(newValue));
}
}
}).mount("#app")
</script>