使用setup语法糖父向子传值时,如果值是从后台获取的数据,可以加一个v-if判断,有数据时再进行组件的渲染
例如
<live v-if="state.list[0]" title="" :list="state.list" :liveTry="state.liveTry"></live>
这个是自己封装的一子组件在父组件里面引用
vue3 setup语法糖不用导入组件直接使用即可,不用注册
<script setup>
import { reactive, onBeforeMount, getCurrentInstance, watch, ref } from 'vue'
import live from './live.vue';
const { proxy } = getCurrentInstance();
const state = reactive({
list: [],
});
let rate = ref('');
onBeforeMount(() => {
getData()
rate.value = proxy.$root.$store.state.rates;
console.log(rate.value);
})
watch(
() => proxy.$root.$store.state.rates, (newVal) => {
console.log(newVal);
rate.value = newVal
}
)
const getData = async () => {
let res = await proxy.$root.$datas("zhibo");
state.list = res.data.liveList;
state.liveTry = res.data.liveTry;
}
</script>
在子组件中使用
<script setup>
import { watch, ref, getCurrentInstance, onMounted } from 'vue'
const props = defineProps(['title', 'list'])
const { proxy } = getCurrentInstance();
let rate = ref('')
watch(
() => proxy.$root.$store.state.rates, (newVal) => {
rate.value = newVal
console.log("🚀 ~ file: live.vue:37 ~ rate.value:", rate.value)
},
{ immediate: true }
)
onMounted(() => {
console.log("🚀 ~ file: live.vue:40 ~ onMounted ~ props:", props)
})
</script>
在template中
<div class="zhibo_vip" v-if="props.liveTry">
<div class="zhibo_vip_model" :style="{ backgroundImage: 'url(' + props.liveTry.imgUrl + ')' }">
<p class="zhibo_vip_model_top">{{ props.liveTry.showLabel }}</p>
<p class="zhibo_vip_model_subLabel">{{ props.liveTry.subLabel }}</p>
<span class="zhibo_vip_model_expire" v-if="props.liveTry.hasExpire">已过期</span>
<span class="zhibo_vip_model_btn" @click="jumpVIP">订阅</span>
</div>
</div>