vue3.0,setup()的使用,Composition Api(组合式api)data,computed,methods,watch

2022年6月10日11:19:45

vue3.0项目创建好之后,来看看一个简单组件内的代码顺便介绍几个特点:

1.组合式api就是指把vue2.0中的datacomputedmethodswatch都集中在3.0中的setup()中
2.setup取代beforeCreatecreated这两个周期,也就是原本放在这两个钩子的内容现在放在setup中
3.在setup里无法再使用this,因为在执行setup的时候组件实例还没创建成功(setup执行在beforeCreate之前)。
4.接收两个参数propscontext(具体的后面讲)
5.代码可读性更高,维护也更方便。当然也完美兼容vue2.x

<template><divclass="home">{{user.name}}--{{user.age}}--{{num}}--{{doubleCount}}<button @click="change"></button></div></template><script>import{ ref, reactive, computed, watch} from'vue'export default{
  name:'Home',setup(){
  	const user= reactive({ name:'jerry', age:18}) // 创建引用类型数据使用reactive
  	const num= ref(6)	// 创建基础数据类型使用ref,使用是用.vulue
	const doubleCount= computed(()=>{return num.value *2})
    // watch的单个值写法,第一个参数是一个getter函数,该函数返回一个响应式对象,要响应式。
    watch(()=> num.value,(newValue, old)=>{
    	// newValue新值,old旧值
    	console.log(newValue, old,'--w')})
    // watch的多个值写法
    /* const num1= ref(11)
    watch([count, count1],([newCount, newCount2],[oldCount, oldCount2])=>{
      console.log([newCount, newCount2],'--',[oldCount, oldCount2],'--w')})
     watch(()=> user,(newValue, oldValue)=>{
    	console.log(newValue, oldValue)},{ deep:true}) // 深入监听user对象内部变化
    watch([count, count1],(newValue, oldValue)=>{
     	console.log(newValue)//[newCount, newCount2]
      	console.log(oldValue)//[oldCount, oldCount2]}) */
    const change=()=>{
      	num.value++}return{
    	user, 
    	num,
    	doubleCount,
    	change}},created(){
  	// vue2.0的内容也还是可以照常用的}}</script>

setup()的两个参数

<script>import{ toRefs, toRef} from'vue'export default{
  name:'Home',
  // 因为props是响应性的,使用解构后会消除其响应性,所以需要使用toRefs, toRef
  // 但是context不具有响应性,可以直接使用解构赋值,但是只能访问attrs, slots, emit, expose
  setup(props, context){
    const{ name}= toRefs(props)
    const{ name0}= toRef(props,'jerry') // toRef的第二个参数就类似于函数形参的默认值
   	const{attrs, slots, emit, expose}= context // 可以打印出来自己去看这几个属性return{}}}</script>

方便维护,便于理解
这样看就不会像vue2.0那样,在维护的时候想要查询某个变量的逻辑,要去data,watch,methos等等里面去找,代码一多,眼睛都给你看画,脑壳看痛

<script>import{ ref, reactive} from'vue'export default{
  name:'Home',
  setup(props, context){
	const num= ref(0)
	/*.
	.这里都是对num的操作代码.
	*/
	
	const user= reactive({name:'jerry'})
	/*.
	.这里都是对user的操作代码.
	*/return{}}}</script>
  • 作者:易子辰丶
  • 原文链接:https://blog.csdn.net/HockJerry/article/details/123799654
    更新时间:2022年6月10日11:19:45 ,共 1929 字。