<script setup>
import { defineProps } from "vue"; // 部分高版本已主动注入 无需重复引入
const props = defineProps({
foo: {
type: String,
default: '默认值',
},
});
console.log(props.foo);// useage
</script>
<script setup>
import { ref,defineExpose } from "vue"; // defineExpose 部分高版本已主动注入
const testData = ref(null);
const refresh = () => {
console.log("refresh");
}
defineExpose({
testData,
refresh
})
</script>
<template>
<SonComponent ref="SonComponent"></SonComponent>
</template>
<script setup>
import SonComponent from './SonComponent';
import { onMounted, ref } from 'vue';
const sonComponentRef = ref(null);
onMounted(() => {
sonComponentRef.value.refresh(); // 调用Son组件 refresh方法
console.log(sonComponentRef.value.testData); // 访问Son组件 testData变量
});
</script>
<script setup>
import { onMounted } from 'vue';
const emit = defineEmits(['callFaterComponent']);
// 父组件@callFaterComponent接受参数
onMounted(() => {
emit('callFaterComponent', 'this is call father data');
});
</script>
实现v-model双向绑定与change方法
<template>
<div>
<input :model-value="modelValue" :value="modelValue" type="text" @input="inputChange" />
</div>
</template>
<script setup>
defineProps({
modelValue: {
type: String,
default: '',
},
});
const emit = defineEmits(['update:modelValue', 'change']);
const inputChange = (e) => {
emit('update:modelValue', e.target.value);
emit('change', e.target.value);
};
</script>
<script setup>
import Api from '@/api/index.js'
const data = await Api.getData()
console.log(data)
</script>
类似computed,传入一个回调函数,将会被立即执行,同时建立参数依赖,当依赖参数发生值变化时,再次执行回调函数
<script setup>
import { ref, watchEffect } from 'vue';
const numA = ref(1);
const numB = ref(2);
const sum = ref(0);
watchEffect(() => {
sum.value = numA.value + numB.value;
console.log('this is sum::', sum.value);
});
setInterval(() => {
numA.value += 1;
numB.value += 2;
}, 1000);
</script>
当numA,numB的值发送变化时,将字段除非回调函数,即sum值得到更新。