ref
在Vue.js中,ref是一个函数,它可以用来定义响应式的数据。可以将任何JavaScript对象变成响应式数据对象。例如:
import { ref } from 'vue';
const count = ref(0);
console.log(count.value); // 输出0
count.value++; // 修改值
console.log(count.value); // 输出1
reactive
reactive也是一个函数,用于将对象转换为响应式数据对象。与ref不同,reactive可以使整个对象变成响应式的,而不仅仅是一个属性。例如:
import { reactive } from 'vue';
const state = reactive({
count: 0,
message: 'Hello World'
});
console.log(state.count); // 输出0
console.log(state.message); // 输出"Hello World"
state.count++; // 修改值
console.log(state.count); // 输出1
reactive 对比 ref
- 相同点:都是用来生成响应式数据
- 不同点
a. reactive不能处理简单类型的数据
b. ref参数类型支持更好,但是必须通过.value做访问修改
c. ref函数内部的实现依赖于reactive函数
computed
computed是一个用于定义计算属性的函数。计算属性是基于响应式数据衍生而来的数据,并且会自动更新。例如:
import { computed, reactive } from 'vue';
const state = reactive({
count: 0
});
const doubleCount = computed(() => {
return state.count * 2;
});
console.log(doubleCount.value); // 输出0
state.count++; // 修改值
console.log(doubleCount.value); // 输出2
defineProps
defineProps用于定义组件的props。它接收一个props定义对象作为参数,并返回一个包含定义的props的响应式代理对象。例如:
import { defineProps } from 'vue';
const props = defineProps({
title: {
type: String,
required: true
},
count: {
type: Number,
default: 0
}
});
defineEmits
defineEmits用于定义组件的emits选项。它接收一个包含事件名的对象作为参数,并返回一个包含定义的事件名的对象。例如:
import { defineEmits } from 'vue';
const emits = defineEmits(['increment', 'decrement']);