从新回归Vue之3.0(二):setup,defineProps,defineEmits,变量,defineExpose

一.在setup()中不能用this

在vue2.x里飞天遁地的this没有了,因为

`setup` 的调用发生在 `data` 、`computed` 或 `methods` 被解析之前,所以它们无法在 `setup` 中被获取,这也是为了避免setup()和其他选项式API混淆。


二.setup推荐用法

<template>
  <h1>{{ msg }}</h1>
</template>
 
<script setup lang="ts">
import { ref } from "vue";
</script>
 
<style scoped>
</style>                       

注意点:

在setup语法糖中导入组件不需要注册声明,直接在视图中使用即可;
默认的vue文件结构发生改变,js默认放到页面顶部,而视图template放到js下面,style放到页面底部;
导入vue文件必须写上文件后缀名.vue, 否则ts无法识别vue文件。
vscode插件不要用vue-format,会导致setup申明消失。
三.defineProps和defineEmits的用法

`defineProps` 和 `defineEmits` API,它们在 `<script setup>` 中都是自动可用的:

defineProps类似之前的props属性

defineEmits类似之前的this.$emit('xxx')的用法

父组件

<template>
  <HelloWorld :msg="msg" @handleClick="handleClick"/>
</template>
 
<script setup lang="ts">
import { ref } from 'vue';
import HelloWorld from './components/HelloWorld.vue'
//data
const msg = ref('欢迎使用vite!')
//methods
const handleClick = (params)=>{
  console.log(params);
}
</script>

子组件

<template>
  <h1>{{ msg }}</h1>
  <button @click="handleClick">点击我调用父组件方法</button>
</template>
 
<script setup lang="ts">
import { ref } from "vue";
// props
const props = defineProps({
  msg: {
    type: String,
    default: "",
  },
});
// emit
const emit = defineEmits(["handleClick"]);
// methods
const handleClick = () => {
  emit("handleClick", "父组件方法被调用了");
};
</script>

四,如何创建变量

import { ref,reactive } from "vue";
// data
let a = ref(2)//ref用来创建基本数据类型
let obj = reactive({name: '张三', age: 2300})//reactive用来创建复杂数据类型
let arr = reactive(['1', '2', '3'])

五.defineExpose的用法

在vue2.x中我们可以通过this.$refs.xxx或者 this.$parent 链获取到的组件的公开实例,

但是使用 <script setup> 的组件是默认关闭的,

为了在 <script setup> 组件中明确要暴露出去的属性,使用 defineExpose 。

假如我们要在子组件里暴露一个handleClick2方法,我们要先定义这个方法

const handleClick2 = () => {
  a.value = 3
  obj.name = '我叫改变'
};

然后整个<script setup> 的最下边用

// defineExpose 统一暴露
defineExpose({
    a,
    obj,
    handleClick2
})

因为如果defineExpose代码行在上,handleClick2申明在下,会报错

posted @ 2022-05-09 09:15  探索之路慢慢  阅读(636)  评论(0编辑  收藏  举报