vue3使用记录

1. 路由跳转

<script setup>
import { useRouter } from "vue-router";
const router = useRouter();
function toDetail() {
  router.push({
    path: "/detail",
  });
}
</script>

2. 注册全局property

// main.js
import utils from "./utils/utils.js";
app.config.globalProperties.$utils = utils;

<script setup>
import { getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance();
const $utils = proxy.$utils;
</script>

3. 通过ref获取dom

// 2.x
<div ref="theDom"></div>
this.$refs.theDom

// 3.x
<div ref="theDom"></div>

import { ref } from 'vue'
const theDom = ref(null)
// 变量名必须与ref定义的名称相同

4. directive

// 2.x
import Vue from 'vue'
Vue.directive('my-directive', {
  bind() {},
  inserted(el, binding, vnode, oldVnode) {},
  update() {},
  componentUpdated() {},
  unbind() {}
})

// 3.x
import { createApp } from 'vue'
const app = createApp({})
app.directive('my-directive', {
  beforeMount() {},
  mounted(el, binding, vnode, oldVnode) {},
  beforeUpdate() {},
  updated() {},
  beforeUnmount() {},
  unmounted() {}
})
// 引入单独封装文件
import directives from "./utils/directives.js";
app.use(directives);

5. 父组件调用子组件内部定义的方法

详细地址

6. 图片的动态引入

// 2.x
require("@/assets/images/xxx.png")

// 3.x
new URL("@/assets/images/xxx.png", import.meta.url).href

7. 获取slot内容

// 2.x
this.$slots[slotName]

// 3.x
// template里
$slots[slotName]
// script里
import { useSlots } from "vue"
let slot = useSlots()

8. 清除响应式对象

let obj = reactive({ count: 0 })

有以下方法:

  • 重新定义对象覆盖
// 直接赋值为新的响应式对象
obj = reactive({});
  • 循环重置每一个属性
// 直接删除属性
for (const key in obj) {
  delete obj[key];
}
// 或重新赋值
let keysArray = Object.keys(obj);
for (const key in keysArray) {
  obj[key] = "";
}
  • 复制空对象
Object.assign(obj, {})

9. 父子组件传参

父传子

// 父组件
<parent-component :data="[1, 2, 3]"></parent-component>

// 子组件
defineProps({
  data: {
    type: Array,
    default: [],
  },
});

子传父

// 父组件
<parent-component @sendData="sendData"></parent-component>
const sendData = (params) => {
  console.log(params);
};

// 子组件
const emit = defineEmits(["sendData"]);
const fn = () => {
  emit("sendData", []);
};
posted @ 2022-12-01 17:46  Li_pk  阅读(47)  评论(0)    收藏  举报