<!-- Use preprocessors via the lang attribute! e.g. <template lang="pug"> -->
<template>
<div id="app">
<h1>{{message}}</h1>
<p>
Learn more with the
<a
href="https://vuejs.org/"
target="_blank"
rel="noopener"
>Vue Docs & Resources</a>.
</p>
<div class="btn_wrapper">
<button @click="doSomething">Say hello.</button>
<button @click="handleChangeAge">changeAge</button>
<button @click="handleChangeStatus">changeStatus</button>
</div>
<div>{{age}}</div>
</div>
</template>
<script>
export default {
data() {
return {
message: 'Welcome to Vue!',
nested: {
a: {
name: 2
}
},
normal: 'normal',
name: 'name',
age: 23,
status: false
};
},
created() {
this.statusUnwatch = this.$watch('status', () => {
console.log('status changed')
})
// this.statusUnwatch = this.$watch('status', {
// handler(){
// console.log('status changed')
// },
// sync: true
// })
},
methods: {
doSomething() {
this.message = 'hello watch'
},
hanlerNameChange(newVal, oldval) {
//...
},
handleChangeAge() {
this.age++
},
handleChangeStatus(){
this.status = !this.status
this.status && this.statusUnwatch()
if(this.status) {
// 因为watcher 异步更新,所以要使用 $nextTick 函数,否则侦听变化的回调函数将不会执行,或者实例化 watcher时增加sync 属性
this.$nextTick(this.statusUnwatch)
}
}
},
watch: {
name: 'hanlerNameChange',
message: [
(newVal) => {
console.log('first watch')
},
(newVal) => {
console.log('second watch')
}
],
nested: {
handler(newVal,oldVal) {
console.log(newVal, oldVal)
},
deep: true,
immediate: true
},
normal(newVal) {
console.log(newVal)
},
age: {
handler(newval) {
console.log('age changed to', newval)
},
before() {
console.log('before age change')
}
}
}
};
</script>
<!-- Use preprocessors via the lang attribute! e.g. <style lang="scss"> -->
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
a,
button {
color: #4fc08d;
}
button {
width: 200px;
background: none;
border: solid 1px;
border-radius: 2em;
font: inherit;
padding: 0.75em 2em;
margin-bottom: 1em;
}
.btn_wrapper {
display: flex;
flex-direction: column;
align-items: center;
}
</style>
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.