监听属性 watch
<h3>监听属性 watch</h3>
<p>watch 监听基础类型,监听的对象不用 .value:</p>
<pre><code class="language-javascript">&lt;template&gt;
&lt;button @click=&quot;change&quot;&gt;更改&lt;/button&gt;
&lt;/template&gt;
&lt;script setup&gt;
import { ref, watch, stopWatch } from &quot;vue&quot;
const num = ref(1)
function change() {
num.value += 1
}
watch(num, (newVal, oldVal) =&gt; {
console.log(num.value) // 2
console.log(&quot;new&quot;, newVal) // 2
console.log(&quot;old&quot;, oldVal) // 1
})
&lt;/script&gt;</code></pre>
<hr />
<p>watch 监听对象,要使用deep属性深度监听,监听的是地址值,所以下边的三行注释是一样的</p>
<pre><code class="language-javascript">&lt;template&gt;
&lt;button @click=&quot;change&quot;&gt;更改&lt;/button&gt;
&lt;/template&gt;
&lt;script setup&gt;
import { ref, watch } from &quot;vue&quot;
let name = ref({
firstName: &quot;Andy&quot;,
lastName: &quot;Zhou&quot;,
})
function change() {
name.value.lastName = &quot;lalala&quot;
}
watch(name, (newVal, oldVal) =&gt; {
console.log(name.value) // {firstName: 'Andy', lastName: 'lalala'}
console.log(&quot;new&quot;, newVal) // {firstName: 'Andy', lastName: 'lalala'}
console.log(&quot;old&quot;, oldVal) // {firstName: 'Andy', lastName: 'lalala'}
}, {
deep: true, //deep 深度监视对象内的内容
})
&lt;/script&gt;</code></pre>
<hr />
<p>watch 监听多个属性</p>
<pre><code class="language-javascript">&lt;template&gt;
&lt;button @click=&quot;change&quot;&gt;更改&lt;/button&gt;
&lt;/template&gt;
&lt;script setup&gt;
import { ref, watch } from &quot;vue&quot;
const num1 = ref(9)
const num2 = ref(90)
function change() {
num1.value = 10
// num2.value = 100
}
watch([num1, num2], (newVal, oldVal) =&gt; {
console.log(&quot;old&quot;, oldVal)
console.log(&quot;new&quot;, newVal)
console.log(num1.value)
})
&lt;/script&gt;</code></pre>
<hr />
<p>watchEffect 立即运行一个函数,全自动监听其依赖</p>
<pre><code class="language-javascript">&lt;template&gt;
&lt;button @click=&quot;change1&quot;&gt;更改1&lt;/button&gt;
&lt;button @click=&quot;change2&quot;&gt;更改2&lt;/button&gt;
&lt;/template&gt;
&lt;script setup&gt;
import { ref, watch, watchEffect } from &quot;vue&quot;
let firstname = ref(&quot;Andy&quot;)
let lastname = ref(&quot;Zhou&quot;)
function change1() {
firstname.value += &quot;~&quot;
}
function change2() {
lastname.value += &quot;~&quot;
}
watchEffect(()=&gt;{
console.log(firstname.value)
console.log(lastname.value)
})
&lt;/script&gt;</code></pre>