vue3和ts的使用

一. setup
变量不在写在data里面, 反而在setup内写。


  • ps:
    1. 使用ref定义字符串,数组等变量值;
    2. 变量赋值需要使用.value;

二. reactive




  • ps:
    1. reactive 接收对象。
    2. 使用时需要使用data.girls方式使用;

三. 添加类型注释

  interface DataProps {
  girls: string[];
  selectGirl: string;
  selectGirlFun: (index: number) => void;
}

cosnt data: DataProps = reactive({
      girls: ["大脚", "刘英", "晓红"],
      selectGirl: "",
      selectGirlFun: (index: number) => {
        data.selectGirl = data.girls[index];
      },
    });

四. toRefs()

import { reactive, toRefs } from "vue";
export default {
  name: "App",
  setup() {
    // const girls = ref(["大脚", "刘英", "晓红"]);
    // const selectGirl = ref("");
    // const selectGirlFun = (index: number) => {
    //   selectGirl.value = girls.value[index];
    // };
    const data: DataProps = reactive({
      girls: ["大脚", "刘英", "晓红"],
      selectGirl: "",
      selectGirlFun: (index: number) => {
        data.selectGirl = data.girls[index];
      },
    });
    const refData = toRefs(data);

    return {
      ...refData,
    };
  },
};

  • ps:
    1. 解决了在template中必须使用data.girls的方式使用变量, 现在可以直接使用变量名称了;

五. 钩子

import {
  reactive,
  toRefs,
  onMounted,
  onBeforeMount,
  onBeforeUpdate,
  onUpdated,
} from "vue";




  • ps
    1. 生命周期需要引用
    2. 什么周期需要卸载setup内
    3. 都是以on开头。
    4. 变化: BeforeDestroy变成了onBeforeUnmount destroyed变成了onUnmounted

生命周期对比


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

六. watch

watch([overText, data.selectGirl], (newValue, oldValue) => {
      console.log(`new--->${newValue}`);
      console.log(`old--->${oldValue}`);
      document.title = newValue[0];  //返回的newValue也是一个数组
  });

  1. teleport

可以定义绑定到dom内;


  1. 使用vuex

      const store = useStore();
const data = {
            startTime: store.state.startTime,
            endTime: store.state.endTime,
            projectId: store.state.projectId
        }

          store.commit('data', data)

  1. 事件

  setup(props, context) {

            context.emit('onShow', userId) 
  }

你可能感兴趣的:(vue3和ts的使用)