<p>查看一些人的 Vue 3 预览教程的一些示例。[目前处于测试阶段]</p>
<p>我找到了两个例子:</p>
<h2>反应式</h2>
<pre class="brush:js;toolbar:false;"><template>
<button @click="increment">
Count is: {{ state.count }}, double is: {{ state.double }}
</button>
</template>
<script>
import { reactive, computed } from 'vue'
export default {
setup() {
const state = reactive({
count: 0,
double: computed(() => state.count * 2)
})
function increment() {
state.count++
}
return {
state,
increment
}
}
}
</script>
</pre>
<h2>参考</h2>
<pre class="brush:js;toolbar:false;"><template>
<div>
<h2 ref="titleRef">{{ formattedMoney }}</h2>
<input v-model="delta" type="number">
<button @click="add">Add</button>
</div>
</template>
<script>
import { ref, computed, onMounted } from "vue";
export default {
setup(props) {
// State
const money = ref(1);
const delta = ref(1);
// Refs
const titleRef = ref(null);
// Computed props
const formattedMoney = computed(() => money.value.toFixed(2));
// Hooks
onMounted(() => {
console.log("titleRef", titleRef.value);
});
// Methods
const add = () => (money.value += Number(delta.value));
return {
delta,
money,
titleRef,
formattedMoney,
add
};
}
};
</script>
</pre>
<p><br /></p>
ref和reactive之间有一些相似之处,因为它们都提供了一种存储数据并允许数据响应的方法。但是:
高水平差异:
const wrappedBoolean = reactive({ value: true })来源:Vue 论坛讨论
反应式
reactive获取对象并向原始对象返回一个响应式代理。示例
import {ref, reactive} from "vue"; export default { name: "component", setup() { const title = ref("my cool title") const page = reactive({ contents: "meh?", number: 1, ads: [{ source: "google" }], filteredAds: computed(() => { return ads.filter(ad => ad.source === "google") }) }) return { page, title } } }说明
在上面,每当我们想要更改或访问
page的属性时,比如说
page.ads,page.filteredAds将通过代理更新。要点
reactive()只接受对象,不 JS 基元(String、Boolean、Number、BigInt、Symbol、null、undefined)ref()正在幕后调用reactive()reactive()适用于对象,并且ref()调用reactive(),因此对象适用于两者ref()有一个用于重新分配的.value属性,reactive()没有这个属性,因此无法重新分配使用
ref()当..'string'、true、23等)reactive()当..ref()的开销总结
ref()似乎是可行的方法,因为它支持所有对象类型并允许使用.value重新分配。ref()是一个很好的起点,但是当您习惯了该 API 后,就会知道reactive()的开销更少,并且您可能会发现它更能满足您的需求需求。ref()用例对于基元,您将始终使用
ref(),但ref()对于需要重新分配的对象(例如数组)很有用。setup() { const blogPosts = ref([]); return { blogPosts }; } getBlogPosts() { this.blogPosts.value = await fetchBlogPosts(); }上面的
reactive()需要重新分配一个属性而不是整个对象。setup() { const blog = reactive({ posts: [] }); return { blog }; } getBlogPosts() { this.blog.posts = await fetchBlogPosts(); }reactive()用例reactive() 的一个很好的用例是一组属于在一起的原语:
const person = reactive({ name: 'Albert', age: 30, isNinja: true, });上面的代码感觉比上面的代码更符合逻辑
const name = ref('Albert'); const age = ref(30); const isNinja = ref(true);有用的链接
如果您仍然迷失方向,这个简单的指南对我有帮助:https://www.danvega.dev/blog/2020/02/12/vue3-ref-vs-reactive/
仅使用
ref()的论点:https://dev.to/ycmjason/thought-on-vue-3-composition-api-reactive-considered-harmful-j8creactive()和ref()存在背后的决策以及其他重要信息,Vue Composition API RFC:https://vuejs.org/guide/extras/composition-api-faq。 html#why-composition-api