🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 计算属性 vs 侦听属性 watch Vue 提供了一种更通用的方式来观察和响应 Vue 实例上的数据变动:**侦听属性**。当你有一些数据需要随着其它数据变动而变动时,你很容易滥用`watch`——特别是如果你之前使用过 AngularJS。然而,通常更好的做法是使用计算属性而不是命令式的`watch`回调 ``` <pre class="calibre13">``` <span class="token"><</span>div id<span class="token">=</span><span class="token4">"demo"</span><span class="token">></span><span class="token1">{</span><span class="token1">{</span> fullName <span class="token1">}</span><span class="token1">}</span><span class="token"><</span><span class="token">/</span>div<span class="token">></span> ``` ``` ``` <pre class="calibre13">``` <span class="token2">var</span> vm <span class="token">=</span> <span class="token2">new</span> <span class="token3">Vue</span><span class="token1">(</span><span class="token1">{</span> el<span class="token1">:</span> <span class="token4">'#demo'</span><span class="token1">,</span> data<span class="token1">:</span> <span class="token1">{</span> firstName<span class="token1">:</span> <span class="token4">'Foo'</span><span class="token1">,</span> lastName<span class="token1">:</span> <span class="token4">'Bar'</span><span class="token1">,</span> fullName<span class="token1">:</span> <span class="token4">'Foo Bar'</span> <span class="token1">}</span><span class="token1">,</span> watch<span class="token1">:</span> <span class="token1">{</span> firstName<span class="token1">:</span> <span class="token2">function</span> <span class="token1">(</span>val<span class="token1">)</span> <span class="token1">{</span> <span class="token2">this</span><span class="token1">.</span>fullName <span class="token">=</span> val <span class="token">+</span> <span class="token4">' '</span> <span class="token">+</span> <span class="token2">this</span><span class="token1">.</span>lastName <span class="token1">}</span><span class="token1">,</span> lastName<span class="token1">:</span> <span class="token2">function</span> <span class="token1">(</span>val<span class="token1">)</span> <span class="token1">{</span> <span class="token2">this</span><span class="token1">.</span>fullName <span class="token">=</span> <span class="token2">this</span><span class="token1">.</span>firstName <span class="token">+</span> <span class="token4">' '</span> <span class="token">+</span> val <span class="token1">}</span> <span class="token1">}</span> <span class="token1">}</span><span class="token1">)</span> ``` ``` ![](https://img.kancloud.cn/53/aa/53aaec58b24301eacaa40af12b635cf0_697x389.png)