簡體   English   中英

Vue3(Vite)直接從子組件訪問父數據

[英]Vue3 (Vite) directly access parent data from child component

我有一個使用 Vue3 Vite (SSG) 沒有 Vuex 的簡單登錄頁面。

我需要將 App.vue 中正在觀看的screenWidthApp.vue給一堆子組件,以便它們根據用戶的 screenWidth 更改圖像。

我可以使用 props 來傳遞這個值,但是為 8 個子組件編寫它們似乎有點麻煩,並且使用組合數據導出或提供/注入肯定是大材小用。

有沒有辦法通過子組件的instance.parent (不起作用)、 $parent.message (Vue2 方式)等簡單地訪問父級的數據?

// Parent:
data() {
  return {
     screenWidth: 123
  }
}

// Child
<div v-if="$parent.screenWidth > 1200">
    img...
</div>

編輯:現在用 props 解決這個問題,因為在 Vite 中似乎沒有其他(工作)解決方案可以用於過去在 Vue2 中很容易的事情。

編輯 2:我現在想到使用 VueUse 的內置useWindowSize可能是一個很好的解決方案。

使用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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM