我有一个简单的登陆页面使用Vue3 Vite (SSG)没有Vuex。
我需要将正在App.vue中监视的一个App.vue值传递给一组子组件,以便它们根据用户的screenWidth更改图像。
我可以使用道具来传递这个值,但是为8个子组件编写它们似乎有点麻烦,而使用组合数据导出或提供/注入显然是过头了。
难道没有一种方法可以简单地从子组件访问父级数据,比如instance.parent (无效)、$parent.message (Vue2方法)等吗?
// Parent:
data() {
return {
screenWidth: 123
}
}
// Child
<div v-if="$parent.screenWidth > 1200">
img...
</div>编辑:现在用道具解决这个问题,因为在Vite中似乎没有其他可行的解决方案,因为在Vue2中曾经很简单。
编辑2:现在我意识到,在useWindowSize中使用VueUse的构建可能是一个很好的解决方案。
发布于 2022-05-09 09:40:00
使用v-model绑定。
父组件(假设安装脚本):
<script setup lang='ts'>
import {ref} from 'vue';
const screenWidth = ref(720);
// use screenWidth as a regulat reactive variable here
</script>
<template>
<Child v-model="screenWidth" />
</template>儿童部分:
<script setup lang="ts">
import {ref, watchEffect} from 'vue';
const props = defineProps<{
modelValue: number;
}>();
const emit = defineEmits<{
(e: 'update:modelValue', value: number): void
}>();
const value = ref(props.modelValue);
watchEffect(() => value.value = props.modelValue);
function setValue(newValue: number) {
value.value = key;
emit('update:modelValue', value.value);
}
</script>
<template>
// Use `value` and `setValue` here
</template>https://stackoverflow.com/questions/72169746
复制相似问题