vue3 开发记录

159 阅读1分钟

1. 子组件传递事件父组件 emits 注意项

  • 方法名和参数建议小驼峰命名法
<!-- 子组件 -->
defineProps({
  modelIndex: String,
})

const emit = defineEmits(['myNextStep']);
function nextStep(step,v) {
  // emit('update:modelIndex', v.id);
  emit('myNextStep',step,v);
}

❗ 不建议使用短横线方法名 emit('my-nextStep',step,v); 会有警告

图片.png

  • 方法名和参数建议短横线
<!-- 父组件 -->
<Child @my-nextStep="nextStep" v-model:model-index="modelIndex"></Child>

function nextStep(val) {
   console.log(val)  // 接收子组件多个参数
}

2. 父组件调用子组件方法问题

  • script setup 语法糖模式
<!-- 子组件 -->
<script setup>
    function getList() {

    }

    // 抛出方法父组件通过实例获取
    defineExpose({
      getList
    })
</script>

//通过`<script setup>`语法糖的写法,其组件是默认关闭的,也就是说如果是通过`$refs`或者`$parents`来访问子组件中定义的值是拿不到的,必须通过**defineExpose**向外暴露你想获取的值才行。
<!-- 父组件 -->
<son-com ref="sonRef"/>

<script setup>
    const sonRef = ref(null);
    const handleClick = () => {
       sonRef.value.getList();
    }
</script>

3. vue3中用refs获取实例问题

  • compositions api 模式
<!-- 父组件 -->
<template>
    <Child ref="child"></Child>
</template>

<script>
import { getCurrentInstance, onMounted } from '@vue/runtime-core'
import Child from './Child.vue'
export default {
    components: {
        Child
    },
    setup() {
        let currentInstance = ''
        onMounted(() => {
            // 只有onmounted中有效
            currentInstance = getCurrentInstance()
        })
        const show = () => {
            currentInstance.ctx.$refs.child.showMsg()
        }
        return {
            show,
            currentInstance
        }
    }
}
</script>

<!-- 子组件 -->
<template>
    <h1>{{ msg }}</h1>
</template>

<script>
import { ref } from "@vue/reactivity";

export default {
    setup() {
        const msg = ref('我是子元素')
        const showMsg = () => {
            console.log(msg.value);
        }
        return {
            msg,
            showMsg
        }
    },

}
</script>
  • script setup 语法糖模式
<!-- 父组件 -->
<template>
    <Child ref="child"></Child>
</template>

<script setup>
import { getCurrentInstance } from '@vue/runtime-core';
import Child from './Child.vue'

let currentInstance = getCurrentInstance()    
function show() {
    currentInstance.ctx.$refs.child.showMsg()
}
</script>


<!-- 子组件 -->
<template>
    <h1>{{ msg }}</h1>
</template>

<script setup>
import { ref } from '@vue/reactivity';

let msg = ref('我是子元素');
const showMsg = () => {
    console.log(msg.value);
}

defineExpose({
    msg,
    showMsg
})
</script>