VUE3 自动引入API(ref,computed, watch,等等)

一、安装

npm install unplugin-auto-import

二、vite.config.js中配置

...
// 引入
import AutoImport from 'unplugin-auto-import/vite'

export default defineConfig({
  plugins: [
    ...
    AutoImport({
      imports: ['vue', 'vue-router'],
      eslintrc: {
        enabled: true
      }
    })

  ],
    ...
})

三、.eslintrc.cjs中配置

module.exports = {
  extends: [
    ...
    './.eslintrc-auto-import.json',
  ],
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 3 中,`watch` 和 `computed` 的用法和 Vue 2 中略有不同。 ## watch ### 监听单个响应式数据 在 Vue 3 中,你可以使用 `watch` 函数来监听一个响应式数据的变化。例如: ```javascript import { watch } from 'vue'; // 在 setup 函数中使用 watch setup() { const count = ref(0); watch(count, (newValue, oldValue) => { console.log(`count 从 ${oldValue} 变为 ${newValue}`); }); return { count }; } ``` 在上面的例子中,我们使用 `watch` 函数监听了 `count` 的变化,并在回调函数中输出了新旧值。 ### 监听多个响应式数据 如果需要监听多个响应式数据的变化,你可以传入一个对象,对象的属性名是需要监听的数据,属性值是回调函数。例如: ```javascript import { watch, ref } from 'vue'; // 在 setup 函数中使用 watch setup() { const count1 = ref(0); const count2 = ref(0); watch({ count1: (newValue, oldValue) => { console.log(`count1 从 ${oldValue} 变为 ${newValue}`); }, count2: (newValue, oldValue) => { console.log(`count2 从 ${oldValue} 变为 ${newValue}`); } }); return { count1, count2 }; } ``` ### 监听非响应式数据 如果需要监听非响应式数据的变化,你可以使用 `watchEffect` 函数。例如: ```javascript import { watchEffect } from 'vue'; // 在 setup 函数中使用 watchEffect setup() { let count = 0; watchEffect(() => { console.log(`count 变为 ${count}`); }); return { count }; } ``` ## computedVue 3 中,你可以使用 `computed` 函数来创建计算属性。例如: ```javascript import { computed, ref } from 'vue'; // 在 setup 函数中使用 computed setup() { const count = ref(0); const doubleCount = computed(() => { return count.value * 2; }); return { count, doubleCount }; } ``` 在上面的例子中,我们创建了一个计算属性 `doubleCount`,它的值是 `count` 的两倍。当 `count` 改变时,`doubleCount` 也会自动更新。 需要注意的是,计算属性的返回值必须是一个响应式数据。如果返回的是普通数据,那么计算属性就没有意义了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值