温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Vue3中的API怎么用

发布时间:2022-01-27 09:39:31 来源:亿速云 阅读:142 作者:iii 栏目:开发技术

这篇文章主要讲解了“Vue3中的API怎么用”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Vue3中的API怎么用”吧!

1. 初始化项目

// ① npm i -g @vue/cli
// ② vue create my-project
// ③ npm install @vue/composition-api -S


// ④ main,js
import Vue from 'vue'
import VueCompositionApi from '@vue/composition-api'
Vue.use(VueCompositionApi)

2. setup方法

setup 是 vue3.x 中新的操作组件属性的方法,它是组件内部暴露出所有的属性和方法的统一API。

2.1 执行时机

setup的执行时机在:beforeCreate 之后 created之前

setup(props, ctx) {
    console.log('setup')
  },
  beforeCreate() {
    console.log('beforeCreate')
  },
  created() {
    console.log('created')
  },
2.2 接受props数据
// 通过 setup 函数的第一个形参,接收 props 数据:
setup(props) {
  console.log(props)
},
// 在 props 中定义当前组件允许外界传递过来的参数名称:
props: {
    p1: String
}
/*
{}
p1: "传值给 com-setup"
get p1: ƒ reactiveGetter()
set p1: ƒ reactiveSetter(newVal)
__proto__: Object
*/
2.3 context

setup 函数的第二个形参是一个上下文对象,这个上下文对象中包含了一些有用的属性,这些属性在 vue 2.x 中需要通过 this 才能访问到,在 vue 3.x 中,它们的访问方式如下:

setup(props, ctx) {
    console.log(ctx)
    console.log(this) // undefined
  },
/*
attrs: Object
emit: ƒ ()
listeners: Object
parent: VueComponent
refs: Object
root: Vue
...
*/

注意:在 setup() 函数中无法访问到 this

3. reactive

reactive 函数接收一个普通函数,返回一个响应式的数据对象。

reactive 函数等价于 vue 2.x 中的 Vue.observable() 函数,vue 3.x 中提供了 reactive() 函数,用来创建响应式的数据对象,基本代码示例如下:

  <div>

    
    <p>当前的 count 值为:{{count}}</p>
    <button @click="count += 1">+1</button>
  </div>






import {reactive} from '@vue/composition-api'
export default {
  setup(props, ctx) {
    // 创建响应式数据对象,得到的 state 类似于 vue 2.x 中 data() 返回的响应式对象
    const state = reactive({ count: 0 })
    state.count += 1
    console.log(state)
     // setup 函数中将响应式数据对象 return 出去,供 template 使用
    return state
  }
}

4. ref

ref() 函数用来根据给定的值创建一个响应式的数据对象,ref() 函数调用的返回值是一个对象,这个对象上只包含一个 .value 属性:

  <div>
    <h4>02.ref.vue 文件</h4>
    <p>refCount:{{refCount}}</p>
    <button @click="refCount += 1">+1</button>
  </div>






import { ref } from '@vue/composition-api'
export default {
  setup() {
    // / 创建响应式数据对象 count,初始值为 0
    const refCount = ref(0)
    // 如果要访问 ref() 创建出来的响应式数据对象的值,必须通过 .value 属性才可以,只有在setup内部才需要 .value 属性
    console.log(refCount.value) // 输出 0
    // 让 refCount 的值 +1
        refCount.value++
    // 再次打印 refCount 的值
        console.log(refCount.value) // 输出 1
    return {
      refCount
    }
  }
}
4.1 在 reactive 对象中访问 ref 创建的响应式数据

当把 ref() 创建出来的响应式数据对象,挂载到 reactive() 上时,会自动把响应式数据对象展开为原始的值,不需通过 .value 就可以直接被访问,例如:

setup() {
  const refCount = ref(0)
  const state = reactive({refCount})
  console.log(state.refCount) // 输出 0
  state.refCount++ // 此处不需要通过 .value 就能直接访问原始值
  console.log(refCount) // 输出 1
  return {
    refCount
  }
}

注意:新的 ref 会覆盖旧的 ref,示例代码如下:

setup() {
  // 创建 ref 并挂载到 reactive 中
  const c1 = ref(0);
  const state = reactive({ c1 });


  // 再次创建 ref,命名为 c2
  const c2 = ref(9);
  // 将 旧 ref c1 替换为 新 ref c2
  state.c1 = c2;
  state.c1++;


  console.log(state.c1); // 输出 10
  console.log(c2.value); // 输出 10
  console.log(c1.value); // 输出 0
}

5. isRef

isRef() 用来判断某个值是否为 ref() 创建出来的对象;应用场景:当需要展开某个可能为 ref() 创建出来的值的时候,例如:

import { ref, reactive, isRef } from "@vue/composition-api";
export default {
  setup() {
    const unwrapped = isRef(foo) ? foo.value : foo
  }
};

6. toRefs

toRefs() 函数可以将 reactive() 创建出来的响应式对象,转换为普通的对象,只不过,这个对象上的每个属性节点,都是 ref() 类型的响应式数据。

  <div>
    <h4>03.toRefs.vue文件</h4>
    <p>{{ count }} - {{ name }}</p>
    <button @click="count += 1">+1</button>
    <button @click="add">+1</button>
  </div>






import { reactive, toRefs } from "@vue/composition-api";
export default {
  setup() {
    // 响应式数据
    const state = reactive({ count: 0, name: "zs" });
    // 方法
    const add = () => {
      state.count += 1;
    };
    return {
      // 非响应式数据
      // ...state,
      // 响应式数据
      ...toRefs(state),
      add
    };
  }
};

7. computed计算属性

7.1 只读的计算属性
  <div>
    <h4>04.computed.vue文件</h4>
    <p>refCount: {{refCount}}</p>
    <p>计算属性的值computedCount : {{computedCount}}</p>
    <button @click="refCount++">refCount + 1</button>

        
    <button @click="computedCount++">计算属性的值computedCount + 1</button>
  </div>






import { computed, ref } from '@vue/composition-api'
export default {
  setup() {
    const refCount = ref(1)
    // 只读
    let computedCount = computed(() => refCount.value + 1)
    console.log(computedCount)
    return {
      refCount,
      computedCount
    }
  }
};
7.2 可读可写的计算属性
  <div>
    <h4>04.computed.vue文件</h4>
    <p>refCount: {{refCount}}</p>
    <p>计算属性的值computedCount : {{computedCount}}</p>
    <button @click="refCount++">refCount + 1</button>
  </div>






import { computed, ref } from '@vue/composition-api'
export default {
  setup() {
    const refCount = ref(1)
    // 可读可写
    let computedCount = computed({
      // 取值函数
      get: () => refCount.value + 1,
      // 赋值函数
      set: val => {
        refCount.value = refCount.value -5
      }
    })
    console.log(computedCount.value)
    // 为计算属性赋值的操作,会触发 set 函数
    computedCount.value = 10
    console.log(computedCount.value)
    // 触发 set 函数后,count 的值会被更新
    console.log(refCount.value)
    return {
      refCount,
      computedCount
    }
  }
};

8. watch

watch() 函数用来监视某些数据项的变化,从而触发某些特定的操作,使用之前需要按需导入:

import { watch } from '@vue/composition-api'
8.1 基本用法
  <div>
    <h4>05.watch.vue文件</h4>
    <p>refCount: {{refCount}}</p>
  </div>






import { watch, ref } from '@vue/composition-api'
export default {
  setup() {
    const refCount = ref(100)
    // 定义 watch,只要 count 值变化,就会触发 watch 回调
    // 组件在第一次创建的时候执行一次 watch
    watch(() => console.log(refCount.value), { lazy: false})
    setInterval(() => {
      refCount.value += 2
    }, 5000)
    return {
      refCount
    }
  }
};
8.2 监视数据源

监视 reactive 类型的数据源:

  <div>
    <h4>05.watch.vue文件</h4>
    <p>count: {{count}}</p> // 不是响应式数据
  </div>






import { watch, ref, reactive } from '@vue/composition-api'
export default {
  setup() {
    const state = reactive({count: 100})
    watch(
      // 监听count
      () => state.count,
      // 如果变换 执行以下函数
      (newVal, oldVala) => {
        console.log(newVal, oldVala)
      },
      { lazy: true }
    )
    setInterval(() => {
      state.count += 2
    }, 5000)
    return state
  }
};

监视 ref 类型的数据源:

export default {
  setup() {
    // 定义数据源
    let count = ref(0);
    // 指定要监视的数据源
    watch(count, (count, prevCount) => {
      console.log(count, prevCount)
    })
    setInterval(() => {
      count.value += 2
    }, 2000)
    console.log(count.value)
    return {
      count
    }
  }
};
8.3 监听多个数据源

监视 reactive 类型的数据源:

export default {
  setup() {
    const state = reactive({count: 100, name: 'houfei'})
    watch(
      // 监听count name
      [() => state.count, () => state.name],
      // 如果变换 执行以下函数
      ([newCount, newName], [oldCount, oldName]) => {
        console.log(newCount, oldCount)
        console.log(newName, oldName)
      },
      { lazy: true} // 在 watch 被创建的时候,不执行回调函数中的代码
    )
    setTimeout(() => {
      state.count += 2
      state.name = 'qweqweewq'
    }, 3000)
    return state
  }
};

监视 ref 类型的数据源:

export default {
  setup() {
    // 定义数据源
    const count = ref(10)
    const name = ref('zs')
    // 指定要监视的数据源
    watch(
      [count, name],
      ([newCount, newName], [oldCount, oldName]) => {
        console.log(newCount, oldCount)
        console.log(newName, oldName)
      },
      { lazy: true}
    )
    setInterval(() => {
      count.value += 2
    }, 2000)
    console.log(count.value)
    return {
      count
    }
  }
};
8.4 清除监视

在 setup() 函数内创建的 watch 监视,会在当前组件被销毁的时候自动停止。如果想要明确地停止某个监视,可以调用 watch() 函数的返回值即可,语法如下:

// 创建监视,并得到 停止函数
const stop = watch(() => {
  /* ... */
})


// 调用停止函数,清除对应的监视
stop()


  <div>

    
    <p>count: {{ count }}</p>
    <button @click="stopWatch">停止监听</button>
  </div>






import { watch, ref, reactive } from "@vue/composition-api";
export default {
  setup() {
    // 定义数据源
    const count = ref(10)
    const name = ref('zs')
    // 指定要监视的数据源
    const stop = watch(
      [count, name],
      ([newCount, newName], [oldCount, oldName]) => {
        console.log(newCount, oldCount)
        console.log(newName, oldName)
      },
      { lazy: true}
    )
    setInterval(() => {
      count.value += 2
      name.value = 'houyue'
    }, 2000)
    // 停止监视
    const stopWatch = () => {
      console.log("停止监视,但是数据还在变化")
      stop()
    }
    console.log(count.value)
    return {
      stop,
      count,
      stopWatch
    }
  }
};
8.5 在watch中清除无效的异步任务

有时候,当被 watch 监视的值发生变化时,或 watch 本身被 stop 之后,我们期望能够清除那些无效的异步任务,此时,watch 回调函数中提供了一个 cleanup registrator function 来执行清除的工作。这个清除函数会在如下情况下被调用:

watch 被重复执行了

watch 被强制 stop 了

Template 中的代码示例如下:

  <div>

    
    <input type="text" v-model="keywords" />
    <p>keywords:--- {{ keywords }}</p>
  </div>

Script 中的代码示例如下:

import { watch, ref, reactive } from "@vue/composition-api";


export default {
  setup() {
    // 定义响应式数据 keywords
    const keywords = ref("");


    // 异步任务:打印用户输入的关键词
    const asyncPrint = val => {
      // 延时 1 秒后打印
      return setTimeout(() => {
        console.log(val);
      }, 1000);
    };


    // 定义 watch 监听
    watch(
      keywords,
      (keywords, prevKeywords, onCleanup) => {
        // 执行异步任务,并得到关闭异步任务的 timerId
        const timerId = asyncPrint(keywords);
        // 如果 watch 监听被重复执行了,则会先清除上次未完成的异步任务
        onCleanup(() => clearTimeout(timerId));
      },
      // watch 刚被创建的时候不执行
      { lazy: true }
    );


    // 把 template 中需要的数据 return 出去
    return {
      keywords
    };
  }
};

9. provide & inject 组件传值

provide() 和 inject() 可以实现嵌套组件之间的数据传递。这两个函数只能在 setup() 函数中使用。父级组件中使用 provide() 函数向下传递数据;子级组件中使用 inject() 获取上层传递过来的数据。

9.1 共享普通数据

app.vue 根组件:

  <div id="app">
    <h2>父组件</h2>
    <button @click="color = 'blue'">蓝色</button>
    <button @click="color = 'red'">红色</button>
    <button @click="color = 'yellow'">黄色</button>

    

    
  </div>






import { ref, provide } from '@vue/composition-api'
import Son from './components/06.son.vue'


export default {
  name: 'app',
  components: {
    'son': Son
  },
  setup() {
    const color = ref('green')
    provide('themecolor', color)
    return {
     color
    }
  }
}

06.son.vue son 组件:

  <div>
    <h4 :>son 组件</h4>

    
  </div>






import { inject } from '@vue/composition-api'
import Grandson from './07.grandson.vue'
export default {
    components: {
    'grandson': Grandson
  },
  setup() {
    const color = inject('themecolor')
    return {
     color
    }
  }
}

07.grandson.vue son 组件:

  <div>
    <h6 :>grandson 组件</h6>
  </div>






import { inject } from '@vue/composition-api'
export default {
  setup() {
    const color = inject('themecolor')
    return {
      color
    }
  }
}
9.2 共享ref响应式数据

app.vue 根组件:

  <div id="app">
    <h2>父组件</h2>

    
  </div>






import { provide } from '@vue/composition-api'
import Son from './components/06.son.vue'


export default {
  name: 'app',
  components: {
    'son': Son
  },
  setup() {
    provide('themecolor', 'red')
  }
}

06.son.vue son 组件:

  <div>
    <h4 :>son 组件</h4>

    
  </div>






import { inject } from '@vue/composition-api'
import Grandson from './07.grandson.vue'
export default {
    components: {
    'grandson': Grandson
  },
  setup() {
    const color = inject('themecolor')
    return {
      color
    }
  }
}

07.grandson.vue son 组件:

template>
  <div>
    <h6 :>grandson 组件</h6>
  </div>






import { inject } from '@vue/composition-api'
export default {
  setup() {
    const color = inject('themecolor')
    return {
      color
    }
  }
}

10. 节点的引用 template ref

10.1 dom的引用
  <div>
    <h4 ref="h4Ref">TemplateRefOne</h4>
  </div>






import { ref, onMounted } from '@vue/composition-api'


export default {
  setup() {
    // 创建一个 DOM 引用
    const h4Ref = ref(null)


    // 在 DOM 首次加载完毕之后,才能获取到元素的引用
    onMounted(() => {
      // 为 dom 元素设置字体颜色
      // h4Ref.value 是原生DOM对象
      h4Ref.value.style.color = 'red'
    })


    // 把创建的引用 return 出去
    return {
      h4Ref
    }
  }
}
10.2 组件的引用

App父组件:

  <div id="app">
    <h2>父组件</h2>
    <button @click="showComRef">展示子组件的值</button>

    
  </div>








import Son from './components/06.son.vue'


export default {
  name: 'app',
  components: {
    'son': Son
  },
  setup() {
    const comRef = ref(null) 
    const showComRef = () => {
      console.log(comRef)
      console.log('str1的值是' + comRef.value.str1)
      comRef.value.setStr1()
    }
    return {
      comRef,
      showComRef
    }
  }
}

06.son.vue子组件:

  <div>
    <h4 :>son 组件</h4>
    <p>{{str1}}</p>
  </div>






import { ref } from '@vue/composition-api'
export default {
  setup() {
    const str1 = ref('这是一个子组件!!')
    const setStr1 = () => {
      str1.value = '被赋值了'
    }
    return {
      str1,
      setStr1
    }
  }
}

11 nextTick

  <div>
    <h4>09.nextTick 组件</h4>
    <p>学习 $nextTick</p>
    <button v-if="isShowInput === false" @click="showInput">展示文本框</button>
    <input type="text" v-else ref="ipt">
  </div>






export default {
  data() {
    return {
      isShowInput: false
    }
  },
  methods: {
    showInput() {
      this.isShowInput = !this.isShowInput
      // console.log(this.$refs)
      this.$nextTick(() => {
        this.$refs.ipt.focus()
      })
    }
  }
}

感谢各位的阅读,以上就是“Vue3中的API怎么用”的内容了,经过本文的学习后,相信大家对Vue3中的API怎么用这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI