• 欢迎大家分享资料!前往留言板评论即可!

Vue3初步使用

合宙 模组资料网 2年前 (2021-05-15) 336次浏览 0个评论 扫描二维码
文章目录[隐藏]

Vue3初步使用:颤抖的手,激动的心。之前也是Vue入门的,现在已忘记的差不多了,借着Vue3的更新,重拾旧忆。。。

使用

使用官网的vue-cli脚手架搭建

建议:在安装之前首先确定环境是否已安装完毕;其次建议安装最新版的vue-cli 4.x

yarn global add @vue/cli
# OR
npm install -g @vue/cli

使用vite工具搭建

使用 npm:

npm init @vitejs/app <project-name> cd <project-name>
npm install npm run dev

使用yarn:

yarn create @vitejs/app <project-name> cd <project-name>
yarn yarn dev

认识Vue3的composition API

组合式API:将底层的方法进行进一步的拆分,暴露出来进行使用;原来的方法只能写在methods里边,但是在vue3中是有一定变化的,要放到setup中去使用;

下面来简单说一下我认为比较重要的API:

createApp

// 先导入createApp模块
import { createApp } from 'vue';
import App from './App.vue';

// 使用createApp方法将我们的入口文件放进去,最后挂载
createApp(App).mount('#app');

这和Vue2还是有一定的差异的,从写法上来看倒是有点类似React

setup

setup函数是Composition API逻辑组织的入口;用来存放所有的方法。。。

export default defineComponent({
  setup() {
    ......
    onMounted(() => {
      console.info("onMounted");
    });
   .......
    return {};
  }
})

Vue3初步使用

onMounted (Vue3)

Vue2(Mounted),Vue多了on

// 先导入onMounted模块
import { onMounted, defineComponent } from 'vue';

export default defineComponent({
    setup () {
        // 使用的时候需要放在setup里边
        onMounted(() => {
            console.log('哈哈哈哈哈哈哈哈')
        })
    }
})

computed

computed是一个函数,callback作为参数,返回Ref对象;也可以接收一个对象形式(对象中只有set和get)作为参数。

import { defineComponent, ref, computed } from "vue";
export default defineComponent({
  setup() {
    const count = ref(0);
    const increment = () => {
      count.value++;
    };
    const double = computed(() => count.value * 2);
    // const double = computed({
    //   get() {
    //     return count.value * 3;
    //   },
    //   set(val) {
    //     console.log(val);
    //     count.value = val - 1;
    //   }
    // });
    return {
      count,
      increment,
      double
    };
  }
});

watch

//监听器
import { reactive, watch } from 'vue';
// 监听getter
const state = reactive({ count: 0 })
watch(
  () => state.count,
  (count, prevCount) => {

  }
)

// 监听ref
const count = ref(0)
watch(count, (count, prevCount) => {

})

watchEffect

const count = ref(0)
watchEffect(() => console.log(count.value))
setTimeout(() => {
  count.value++
}, 100)

停止侦听,当 watchEffect 在组件的 setup() 函数或生命周期钩子被调用时, 侦听器会被链接到该组件的生命周期,并在组件卸载时自动停止。

const stop = watchEffect(() => {
    .............
})
stop()

ref

接受一个参数值并返回一个响应式且可改变的 ref 对象。ref 对象拥有一个指向内部值的单一属性 .value。

const count = ref(0)
console.log(count.value)   0

count.value++
console.log(count.value)    1

reactive

实现响应式的一种方法。。。

Vue3的声明周期对应:

beforeCreate -> 使用 setup() 
created -> 使用 use setup() 
beforeMount -> onBeforeMount 
mounted -> onMounted 
beforeUpdate -> onBeforeUpdate 
updated -> onUpdated 
beforeDestroy-> onBeforeUnmount 
destroyed -> onUnmounted 
activated -> onActivated 
deactivated -> onDeactivated 
errorCaptured -> onErrorCaptured

可能存在描述不准确的地方,欢迎指正。。。bye


转载请注明原文链接:Vue3初步使用
喜欢 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址