Vue3.0中:变量必须return出来才能在template中才能使用
Vue3.2后:基于script setup 语法糖,无需return
下面案例均基于script setup 语法糖👊
定义数据
ref:定义基本类型
<div>{{ageRef}}</div>
<script setup>
const ageRef = ref(19)
onMounted(() => {
console.log(ageRef.value)
})
</script>
reactive:定义复杂数据类型
<script setup>
const data = reactive({
items: [1, 2, 3],
tempObj: {}
});
// 模拟接口返回值更新数据
const updateArray = () => {
const newArray = [4, 5, 6];
data.items = newArray;
data.tempObj = {'name': 'yf'};
};
</script>
数据通信
defineProps:子组件接收父组件传值
<template>
<div>{{childProps}}</div>
</template>
<script setup>
const props = defineProps({
childProps: {
type: String,
default: 'a'
}
});
</script>
defineEmits:子组件向父组件触发事件
<template>
<button @click="sendMessage"></button>
</template>
import { defineEmits } from 'vue'
<script setup>
const emit = defineEmits(["acceptMessage"]); // 定义emit
const sendMessage = () => {
emit('acceptMessage', 'a')
}
</script>
defineExpose:父组件中调用子组件方法
子组件:
<script setup>
const goSomePage = () => {
window.location.href = 'https://a.b.cn'
}
defineExpose({
goSomePage
});
</script>
父组件:
<template>
<button @click="goSomePage">跳转</button>
<Child ref="child" />
</template>
<script setup>
import { ref } from "vue"
import Child from "./Child.vue"
const child = ref("child");
const { goSomePage } = child.value;
</script>