Vue 中setup的特性

编程入门 行业动态 更新时间:2024-10-22 05:06:44

Vue 中setup的<a href=https://www.elefans.com/category/jswz/34/1769892.html style=特性"/>

Vue 中setup的特性

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

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

<template><h3>我是父组件</h3><hr /><Child :name="info.name" :age="info.age"></Child>
</template><script setup>
// 引入组件
import Child from '../components/Child';
// 引入 reactive 函数
import { reactive } from 'vue';
// 创建 reactive 数据
let info = reactive({ name: "张三", age: 18 });
</script>

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

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

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

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

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

<template><h3>我是父组件</h3><hr /><Child @myEvent="add"></Child>
</template><script setup>
// 引入组件
import Child from '../components/Child';
// 创建方法
const add = (value) => {console.log('我是父组件', value);
}
</script>

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

<template><h3>我是子组件</h3><button @click="isShow">传递数据</button>
</template><script setup>
// 注册父组件传递的自定义事件
const emit = defineEmits(['myEvent']);
// 创建方法调用自定义事件
const isShow = () => {emit('myEvent', 666);
}
</script>

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

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

<template><h3>我是父组件</h3><button @click="isShow = !isShow">切换组件</button><hr /><!-- 如果 isShow 为 true 就显示 A 组件,否则显示 B 组件 --><component :is="isShow ? A : B"></component>
</template><script setup>
// 引入组件
import A from '../components/A';
import B from '../components/B';
// 引入 ref 函数
import { ref } from 'vue';
// 创建 ref 数据
const isShow = ref(true);
</script>

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

<template><h3 class="title">我是父组件</h3><button @click="state = 'blue'">按钮</button>
</template><script setup>
// 引入 ref 函数
import { ref } from "vue";
// 创建 ref 数据
let state = ref('red');
</script><style scoped>
.title {/* 使用 v-bind 绑定 CSS 样式 */color: v-bind('state');
}
</style>

原创作者:吴小糖

创作时间:2023.10.19

更多推荐

Vue 中setup的特性

本文发布于:2023-12-07 12:36:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1671219.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:特性   Vue   setup

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!