vue3.0组合式api的使用小结
前言
在Vue.js 3.0中,相比于2.x,最大的改变之一就在于引入了Composition API(也称为Function-based API)。相比之前的Options API,在复杂组件中更加便捷高效,使得代码更加容易维护等等。本文将详细介绍如何使用Vue3.0的组合式API。
安装Vue3.0
在安装Vue3.0之前,需要先卸载所安装的Vue2.x版本:
npm uninstall vue
接着,我们可以通过下列命令安装Vue3.0:
npm install vue@next
组合式API的使用
在Vue3中,我们可以通过defineComponent
函数定义组件并使用组合式API。如下:
import { defineComponent } from "vue";
export default defineComponent({
setup() {
// ...
}
})
reactive
Vue3中使用reactive
创建响应式对象:
import { reactive } from "vue";
const state = reactive({
count: 0
});
console.log(state.count) // 输出0
// 修改count值
state.count++
console.log(state.count) // 输出1
ref
与reactive
配合使用时,我们可以使用ref
将普通值变为响应式:
import { reactive, ref } from "vue";
const state = reactive({
count: ref(0)
});
console.log(state.count.value) // 输出0
// 修改count值
state.count.value++
console.log(state.count.value) // 输出1
computed
Vue3中使用computed
创建计算属性:
import { reactive, computed } from "vue";
const state = reactive({
count: ref(0)
});
const doubleCount = computed(() => state.count.value * 2)
console.log(doubleCount.value) // 输出0
// 修改count值
state.count.value++
console.log(doubleCount.value) // 输出2
watch
Vue3中使用watch
来监听响应式数据的变化:
import { reactive, watch } from "vue";
const state = reactive({
count: ref(0)
});
watch(
() => state.count.value,
(newValue, oldValue) => {
console.log(`count值从${oldValue}变为${newValue}`);
}
);
// 修改count值
state.count.value++ // 输出count值从0变为1
生命周期
Vue3中的生命周期函数也有所更改,通过onMounted
等函数使用:
import { defineComponent, onMounted } from "vue";
export default defineComponent({
setup() {
onMounted(() => {
console.log("组件已挂载");
});
}
});
示例说明
以下是一个简单的示例,计算出两个数的和并显示:
<template>
<div>
<input type="number" v-model="num1" />
<input type="number" v-model="num2" />
<div>{{ sum }}</div>
</div>
</template>
<script>
import { defineComponent, reactive, computed } from "vue";
export default defineComponent({
setup() {
const state = reactive({
num1: 0,
num2: 0
});
const sum = computed(() => state.num1 + state.num2);
return {
state,
sum
};
}
});
</script>
以上代码中使用了组合式API的特性,创建响应式对象和计算属性。
以下是另一个示例,实现表单输入验证:
<template>
<div>
<input type="text" v-model="username" />
<div>{{ validateUsernameMessage }}</div>
</div>
</template>
<script>
import { defineComponent, ref, computed } from "vue";
export default defineComponent({
setup() {
const username = ref("");
const validateUsernameMessage = computed(() => {
if (username.value.length === 0) {
return "请输入用户名";
} else if (username.value.length < 4) {
return "用户名长度不能小于4位";
} else {
return "";
}
});
return {
username,
validateUsernameMessage
};
}
});
</script>
以上代码中使用了组合式API的特性,将普通值变为响应式并使用计算属性进行数据处理。同时,也演示了如何在前端进行简单的表单输入验证。
结语
我会在未来的文章中描述更多Vue.js的相关主题。感谢你的阅读,如有不当之处敬请指出。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:vue3.0组合式api的使用小结 - Python技术站