vue3 使用经验合集

123 阅读1分钟

01.ref绑定dom元素

创建 ref:const xxxRef = ref() 
绑定ref属性到标签上: ref="xxxRef" 
通过xxxRef.value访问dom

02.路由取参数

比如地址 http://127.0.0.1:5173/?code=123123,

我们要获取code参数可以路由route获取,注意是route.query

<script setup> 
import { useRoute } from 'vue-router' 
const route = useRoute() 
onMounted(()=>{
    console.log(route.query) // 地址兰参数
}) 
</script>

03.vue3 子向父传值,父亲接收

子组件:

import { defineEmits } from 'vue' 
const emit = defineEmits(['showModel']) 
const handleClick = ()=>{ 
    emit('showModel', value)
}

父组件:

<child @showModel="show" />
import child from './child.vue'
const show = (value)=>{
    console.log(value) 
}

04.computed

<el-tooltip class="box-item" effect="dark" :content="content" placement="right">
  <el-button type="primary" @click="handleClick">test</el-button>
</el-tooltip>
    
import { computed } from 'vue'
    
const content = computed(() => {
      const { type } = route.query
      if (type == 'a') {
        return 'aaa'
      } else if (type == 'b') {
        return 'bbb'
      } else if (type == 'c') {
        return 'ccc'
      }
})

05.watch

watch(
  () => route.path,
  (newValue, oldValue) => {
    console.log(`新值:${newValue} ——— 老值:${oldValue}`);
    activeIndex.value = newValue;
  },
  { deep: true }
);

06.props

<template>
  <div>
    <h1>{{ title }}</h1>
    <p>Count: {{ count }}</p>
  </div>
</template>

<script setup>
// 定义props
const props = defineProps({
  title: {
    type: String,
    required: true,
    default: 'Default Title'
  },
  count: {
    type: Number,
    default: 0
  }
});
</script>

07.computed计算props

<script setup>
import { onMounted, computed } from 'vue'

const props = defineProps({
  cMarkerData: {
    type: Object,
  },
})

const cName = computed(() => {
  return props.cMarkerData.name
})

const imgSrc = computed(() => {
  return `props.cMarkerData.img`
})

</script>

08.toRaw

image.png

09.动态设置并修改title

// main.js
// 定义 title 指令
app.directive('title', {
  // 当被绑定的元素挂载到 DOM 上时调用
  mounted(el, binding) {
    document.title = binding.value
  },
  // 当绑定的值更新时调用
  updated(el, binding) {
    document.title = binding.value
  },
})

// 使用
<div v-title="'管理平台'"></div>