计算属性 computed
<h3>计算属性 computed</h3>
<p>首次在页面上渲染会被调用一次,之后会被缓存:</p>
<pre><code class="language-javascript">&lt;template&gt;
&lt;input type=&quot;text&quot; v-model=&quot;firstname&quot;&gt;
&lt;input type=&quot;text&quot; v-model=&quot;lastname&quot;&gt;
&lt;p&gt;{{ fullname }}&lt;/p&gt;
&lt;/template&gt;
&lt;script setup&gt;
import { ref, computed } from 'vue'
let firstname = ref(&quot;Andy&quot;)
let lastname = ref(&quot;Zhou&quot;)
let fullname = computed(() =&gt; {
console.log('computed')
return firstname.value + lastname.value
})
&lt;/script&gt;</code></pre>
<p>由于被缓存,所以虽然页面上渲染了三次,但是 console.log 也只有一次:</p>
<pre><code class="language-javascript">&lt;template&gt;
&lt;input type=&quot;text&quot; v-model=&quot;firstname&quot;&gt;
&lt;input type=&quot;text&quot; v-model=&quot;lastname&quot;&gt;
&lt;p&gt;{{ fullname }}&lt;/p&gt;
&lt;p&gt;{{ fullname }}&lt;/p&gt;
&lt;p&gt;{{ fullname }}&lt;/p&gt;
&lt;/template&gt;
&lt;script setup&gt;
import { ref, computed } from 'vue'
let firstname = ref(&quot;Andy&quot;)
let lastname = ref(&quot;Zhou&quot;)
let fullname = computed(() =&gt; {
console.log('computed')
return firstname.value + lastname.value
})
&lt;/script&gt;</code></pre>
<p>在其依赖变化时也会再调用:(第一次是渲染,第二次是改变了 firstname)
<img src="https://www.showdoc.com.cn/server/api/attachment/visitFile?sign=0c439e5b3517bcd8619071226218a8c0&amp;file=file.png" alt="" /></p>
<p>想获取计算属性的值,也得用 .value ,但是是只读的不可以更改
<img src="https://www.showdoc.com.cn/server/api/attachment/visitFile?sign=2c7f5aba2242a0efb3641c29469cbee2&amp;file=file.png" alt="" /></p>
<hr />
<p><strong>计算属性和方法的区别:</strong></p>
<ul>
<li>计算属性:首次在页面上渲染会被调用一次,之后会被缓存,在其依赖变化时才会再调用</li>
<li>方法:总会在渲染时被调用</li>
</ul>
<hr />
<p><strong>应用1:子组件用计算属性监听父组件props值的变化:</strong></p>
<pre><code class="language-javascript">父组件:将 name 传给子组件
&lt;template&gt;
&lt;button @click=&quot;change&quot;&gt;click&lt;/button&gt;
&lt;Child :name=&quot;name&quot;&gt;&lt;/Child&gt;
&lt;/template&gt;
&lt;script setup&gt;
import { ref } from &quot;vue&quot;;
import Child from &quot;@/components/Child.vue&quot;;
let name = ref(&quot;Andy&quot;);
const change = () =&gt; {
name.value = &quot;aaa&quot;;
};
&lt;/script&gt;</code></pre>
<pre><code class="language-javascript">子组件:子组件监听 name 的变化
&lt;template&gt;
&lt;div :data=&quot;newname&quot;&gt;&lt;/div&gt;
&lt;/template&gt;
&lt;script setup&gt;
import { inject, watch, computed } from &quot;vue&quot;;
const props = defineProps({
name: {
type: String,
},
});
const newname = computed(() =&gt; {
console.log(props.name);
return props.name;
});
&lt;/script&gt;</code></pre>
<p>刚开始控制台打印 Andy,点击按钮后打印 aaa
<img src="https://www.showdoc.com.cn/server/api/attachment/visitFile?sign=faefc0f74926be74fa3a088a61ed8237" alt="" /></p>