欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

vue3.0新语法的基本使用

程序员文章站 2022-06-15 15:02:32
...
<template>
  <!-- <div>count:{{ count }}</div>
  <div>double:{{ double }}</div> -->
  <div>count:{{ count }}</div>
  <el-button @click="add">点击</el-button>
</template>
import { reactive, ref, toRefs, toRef, computed, watch, watchEffect } from 'vue';

ref方法与reactive方法的使用
ref的基本使用

const count = ref(0);
    setTimeout(() => {
      count.value++;
    }, 1000);
    return {
      count
    };

reactive的基本使用

const state = reactive({
      count: 0
    });
    const { count } = toRefs(state); // 把普通的数据转成ref()方法所对应的响应式数据
    setTimeout(() => {
      state.count++;
    }, 1000);
    return {
      count
    };

toRefs的基本使用

const state = reactive({
      count: 0
    });
    const { count } = toRefs(state);
    setTimeout(() => {
      state.count++;
    }, 1000);
    return toRefs(state);

计算属性

const count = ref(1);
    const double = computed(() => count.value * 2);
    setTimeout(() => {
      count.value++;
    }, 1000);
    return {
      count,
      double
    };
    
const state = reactive({
      count: 1,
      double: computed(() => {
        return state.count * 2;
      })
    });
    setTimeout(() => {
      state.count++;
    }, 1000);
    return toRefs(state);

事件

const count = ref(0);
    const add = () => {
      count.value++;
    };
    return {
      count,
      add
    };

副作用

const count = ref(0);
    const add = () => {
      count.value++;
      if (count.value === 5) {
        stop();
      }
    };
    const stop = watchEffect(async (cancel) => {
      await new Promise(function (resolve, reject) {
        console.log(count.value); // 监听count值得变化
        resolve();
      });
      cancel(() => {
        // 会在异步之前进行触发,清除副作用
        console.log('cancel');
      });
    });
    return {
      count,
      add
    };

事件监听

const count = ref(0);
    const add = () => {
      count.value++;
    };
    watch(count, (count, prevCount) => {
      console.log(count, prevCount);
    });
    return {
      count,
      add
    };
相关标签: VUE技术栈 vue.js