• Vue 中setup的特性


    特性四:父传子组件传参【defineProps】:

    父组件(传递数据):利用自定义属性传递数据。

    1. <template>
    2. <h3>我是父组件h3>
    3. <hr />
    4. <Child :name="info.name" :age="info.age">Child>
    5. template>
    6. <script setup>
    7. // 引入组件
    8. import Child from '../components/Child';
    9. // 引入 reactive 函数
    10. import { reactive } from 'vue';
    11. // 创建 reactive 数据
    12. let info = reactive({ name: "张三", age: 18 });
    13. script>

    子组件(接收数据):使用 defineProps 接收数据。

    1. <template>
    2. <h3>我是子組件h3>
    3. <p>{{ name }} : {{ age }}p>
    4. template>
    5. <script setup>
    6. // 接收父组件传递的数据
    7. const props = defineProps(['name', 'age']);
    8. script>

    :defineProps 用于接收父组件传递的数据,不需要引入,可以直接使用。

    特性五:子传父组件传参【defineEmits】

    父组件(接收数据):创建自定义事件,利用方法接收数据。

    1. <template>
    2. <h3>我是父组件h3>
    3. <hr />
    4. <Child @myEvent="add">Child>
    5. template>
    6. <script setup>
    7. // 引入组件
    8. import Child from '../components/Child';
    9. // 创建方法
    10. const add = (value) => {
    11. console.log('我是父组件', value);
    12. }
    13. script>

    子组件(传递数据):使用 defineEmits 注册自定义事件传递数据。

    1. <template>
    2. <h3>我是子组件h3>
    3. <button @click="isShow">传递数据button>
    4. template>
    5. <script setup>
    6. // 注册父组件传递的自定义事件
    7. const emit = defineEmits(['myEvent']);
    8. // 创建方法调用自定义事件
    9. const isShow = () => {
    10. emit('myEvent', 666);
    11. }
    12. script>

    :defineEmits 用于注册自定义事件,不需要引入,可以直接使用。

     特性六:使用动态组件【component】:

    1. <template>
    2. <h3>我是父组件h3>
    3. <button @click="isShow = !isShow">切换组件button>
    4. <hr />
    5. <component :is="isShow ? A : B">component>
    6. template>
    7. <script setup>
    8. // 引入组件
    9. import A from '../components/A';
    10. import B from '../components/B';
    11. // 引入 ref 函数
    12. import { ref } from 'vue';
    13. // 创建 ref 数据
    14. const isShow = ref(true);
    15. script>

     特性七:使用 v-bind 绑定 CSS 样式:

    1. <template>
    2. <h3 class="title">我是父组件h3>
    3. <button @click="state = 'blue'">按钮button>
    4. template>
    5. <script setup>
    6. // 引入 ref 函数
    7. import { ref } from "vue";
    8. // 创建 ref 数据
    9. let state = ref('red');
    10. script>
    11. <style scoped>
    12. .title {
    13. /* 使用 v-bind 绑定 CSS 样式 */
    14. color: v-bind('state');
    15. }
    16. style>

    原创作者:吴小糖

    创作时间:2023.10.19

  • 相关阅读:
    写在 Chappyz 即将上所之前:基于 AI 技术对 Web3 营销的重新定义
    第三章:form表单
    数据驱动 vs 关键字驱动:对搭建UI自动化测试框架的探索
    SpringBoot整合RabbitMQ实现延迟队列功能
    js的变量赋值的问题
    flutter在导航栏处实现对两个列表的点击事件
    【MySQL知识体系】第1章 初识 MySQL
    Linux中的dpkg指令(dpkg -l | grep XXX等)
    Android Java exception 介绍
    零信任产生的历史背景
  • 原文地址:https://blog.csdn.net/xiaowude_boke/article/details/133934611