Vue使用小技巧

2025-10-11

在 Vue 中获取网址栏内的内容:

new URLSearchParams(window.location.search).get('productName');

import { useRoute } from 'vue-router';
const route = useRoute();
route.query.productName

同时使用v-model和ref 方法控制组件的状态

const props = defineProps(['modelValue']);
const emit = defineEmits(['update:modelValue']);
const innerValue = ref(false);

const show = computed({
  get: () => {
    return props.modelValue !== undefined ? props.modelValue : innerValue.value;
  },
  set: (val) => {
    if (props.modelValue !== undefined) {
      emit('update:modelValue', val);
    } else {
      innerValue.value = val;
    }
  }
});

function open() {
  show.value = true;
}
function close() {
  show.value = false;
}

defineExpose({
  open,
  close
});

NEXT
[Keep-alive] 手动控制已缓存组件的销毁