setup语法糖

113 阅读1分钟

setup语法糖:

在script标签上添加setup属性,则该组件将采用setup语法糖

在setup中定义的变量和方法,在模板中可以直接使用,不用return

响应式数据

<template>
  <div>
    <h3>ref:{{ mytext }}</h3>
    <h3>reactive:{{ obj.myname }} -- {{ obj.myage }}</h3>
    <h3>toRefs:{{ myname }} -- {{ myage }}</h3>
    <button @click="editClick">修改</button>
  </div>
</template>

<script setup>
import { reactive, ref, toRefs } from "vue";

// ref
const mytext = ref("111");
// reactive
const obj = reactive({
  myname: "cxm",
  myage: 18,
});
//toRefs
// 原理就是:解构赋值
const { myname, myage } = toRefs(obj);
// 修改
const editClick = () => {
  // 修改ref,记得 .value
  mytext.value = "哈哈哈红红火火恍恍惚惚";
  // 修改reactive
  obj.myname = "Caoxinmei";
  obj.myage = 21;
};
</script>

父子通信

  1. 导入组件:
    • import导入后,直接在父组件中使用
    • 不用再写components,因为seyup内部已经帮我们完成了这一操作
  2. 父子通信:
    • 父传子:const props = defineProps({传入的数据});
    • 子传父:const emit = defineEmits()

父组件

<template>
  <div>
    <Child title="标题" :isrightShow="true" @myevent="ChildData" />
  </div>
</template>

<script setup>
import Child from "./components/Child.vue"; // 导入即注册

const ChildData = (e) => {
  console.log("父组件接收到的信息", e);
};
</script>

子组件

<template>
  <div>
    <h1>logo</h1>
    <h2>{{ props.title }}</h2>
    <button v-if="props.isrightShow" @click="handleClick">right</button>
  </div>
</template>

<script setup>
// ------------ 父传子 ------------
// 简单写法
// const props = defineProps(["title"]);
// 带有数据验证写法
const props = defineProps({
  title: String,
  isrightShow: {
    type: Boolean,
    default: true, // 默认值为true
  },
});

// ------------ 子传父 ------------
const emit = defineEmits();

const handleClick = () => {
  // 发送消息给父组件
  // emit(父组件中的事件名称, 传递给父组件的数据)
  emit("myevent", "hello111111");
};
</script>

<style lang="scss" scoped>
div {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0px 20px;
  width: 500px;
  h2 {
    flex: 1;
    text-align: center;
  }
}
</style>