vue中的<script setup>与<script>

<script setup>是在vue3.2之后新增的语法糖,简化了API的写法

1.声明的变量无需return,可以直接在模板中使用,实现了顶层的绑定

2.引入组件会自动注册,无需再使用components


<script>
export default {
data() {
return {
dialogVisible: false
};
},
};
</script>
------------------------------------
<
script setup> import {ref} from "vue"; const dialogVisible=ref(true) </script>

3.使用defineProps接收父组件传递的值,返回的是props对象其中的值是只读的,可以在模板中直接使用,defineEmits获取父组件的自定义事件,defineExpose属性/方法对外暴露

<template>
<p>父组件</p>
<child ref="childRef" :value="parentValue" @func="func"/>
</template>

<script setup>
import child from "./child";

const parentValue = ref('我是爸爸');
const func = (params) => {
parentValue.value = params
};

const childRef = ref(null);
onMounted(()=>{
// 调用子组件中的参数和函数
console.log(childRef.value.childValue);
childRef.value.childFn();
});
</script>

<script>
export default {
name: "parent"
}
</script>
<--! -------------------------------------------------------->

<template>
<p>子组件</p>
<p>{{ value }}</p>
<button @click="emit('func', '哈哈哈')">点击</button>
</template>

<script setup>
import { defineProps, defineEmits, defineExpose } from 'vue'

// 接收父级传过来的参数
const props = defineProps(["value"]);
// 接收父级传过来的方法
const emit = defineEmits(["func"]);

const childValue = '我是儿子';
const childFn = () => {
console.log("我是子组件中的方法");
}

// 将参数childValue和函数childFn暴露给父组件
defineExpose({
childValue,
childFn
});
</script>

<script>
export default {
name: "child"
}
</script>

 

posted @ 2024-04-09 20:14  天启A  阅读(718)  评论(0)    收藏  举报