likes
comments
collection
share

Vue3组合式apiscript setup提案使用emitprop组件通信

作者站长头像
站长
· 阅读数 618

在Vue3组合式api开发中,所有模板中使用的变量都需要return暴露模板,这样会给开发者增加很多心智负担,所以又有了提案script setup

之前:

<template>
{{mes}}
</template>
<script>
import {ref} from 'vue'
export default {
setup() {
  let mes=ref('我是加载信息')
}
}
</script>

提案:

<template>
  {{ mes }}
</template>
<script setup="prop,{emit}">
import {ref} from 'vue'
  let mes=ref('我是加载信息')
  emit(函数命,参数)//子传父
  console.log(prop.名字);//获取父组件的传值
</script>

但是在我开发中使用发现变量名字无需return,但是props和ctx参数无法使用,还报出了一些错误

发现相关报错信息狗,去推特询问作者了尤雨溪,并且得到了回复:

Vue3组合式apiscript setup提案使用emitprop组件通信

简单的看就是我使用的方法过时了,不在使用,在去GitHub察看最新方案后,整理出:

<template>
{{mes}}
<组件></组件>
</template>
<script setup>
import {defineEmit, defineProps, ref} from 'vue'
import 组件 from '@/components/组件名字'
let mes=ref('我是文字消息');

let emit=defineEmit();
emit('函数名字',参数)//子>父

let prop=defineProps({
  name:type
})
console.log(prop.name);//获取父组件的值
</script>

变化:

  1. prop,emit等参数需要引入(推荐使用vscode函数内使用会直接帮助您引入)
  2. 组件不在components需要定义只需引入
  3. 双向绑定变量不在需要return全部暴露模板