函式控制 - daniel-qa/Vue GitHub Wiki

函式控制

函式類型

函式類型 說明
箭頭函式 (=>) 簡單,沒有 this,適合用於 setup 中的常見需求。適合處理資料或事件等簡單操作。
傳統函式 (function) 需要 this 或較複雜的邏輯時使用。可以在方法內處理更多業務邏輯。
暴露函式給父組件 (defineExpose()) 用於將子組件內的函式暴露給父組件,讓父組件可以調用。

1 箭頭函式 (=>) 範例:

const removeAction = (index) => {
  // 程式內容
};

2 傳統函式範例:

function removeAction(index) {
  // 程式內容
};

果你直接使用 function 關鍵字來定義函式,則不需要使用 const。這樣的函式會被自動提升(hoisted),即可以在函式定義之前調用。

3 defineExpose() 範例:

<script setup>
import { ref, defineExpose } from 'vue';

const count = ref(0);

// 定義一個方法
const increment = () => {
  count.value++;
};

// 使用 defineExpose() 暴露函式
defineExpose({
  increment
});
</script>
  • 說明:

用途: defineExpose() 用來將組件內部的函式或變數暴露給父組件。父組件可以通過 ref 來調用子組件的函式。

適用場景: 當你需要在父組件中控制子組件的行為或操作子組件的方法時,使用 defineExpose()。

  • 父組件使用:
<template>
  <Child ref="childRef" />
  <button @click="callIncrement">Increment in Child</button>
</template>

<script setup>
import { ref } from 'vue';
import Child from './Child.vue';

const childRef = ref(null);

const callIncrement = () => {
  // 透過 ref 調用子組件的 increment 函式
  childRef.value.increment();
};
</script>
  • 說明:

父組件通過 ref 來訪問子組件,並調用 increment 函式。

defineExpose() 使得 increment 函式能夠被父組件調用。


  • 將數組設為空
// 不需要參數,直接清空数组
const removeAction = () => {
  actions.value = []; // 將數組設為空
};

expose

如何使用 expose?

  • 1 . 子組件定義要暴露的內容

使用 expose 將子組件的特定方法或屬性暴露給父組件。

<!-- 子組件 -->
<template>
  <div>我是子組件</div>
</template>

<script setup>
function someMethod() {
  console.log('這是子組件暴露的方法');
}

const message = '這是暴露的屬性';

expose({
  someMethod,
  message,
});
</script>
  • 2 .父組件訪問暴露的接口

父組件通過 ref 和 ref.value 調用暴露的內容。

<!-- 父組件 -->
<template>
  <ChildComponent ref="childRef" />
  <button @click="callChildMethod">呼叫子組件方法</button>
</template>

<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';

const childRef = ref(null);

function callChildMethod() {
  console.log(childRef.value.message); // 訪問暴露的屬性
  childRef.value.someMethod();        // 呼叫暴露的方法
}
</script>

$refs

$refs 是非響應式的:$refs 只在 DOM 加載完成後才可用,若在組件尚未加載完成前調用,會得到 undefined。

組件的設計應儘量避免直接操作 $refs:這種方法耦合度較高,應優先考慮透過父子組件的事件通信或 props 傳遞來實現功能。

在 Vue.js 中,this.$refs 是一个对象,存储了通过 ref 属性标记的 DOM 元素或子组件实例的引用。你可以通过 this.$refs 直接访问这些引用,进行操作。

可以訪問函式,數據組,變數。

  • ref 是 Vue 提供的功能,用于直接操作组件实例,常见用法如 this.$refs.paperEdit。

  • refId 是自定义属性,只有组件内部对其有具体实现时才有意义。

在你的代码中,refId="paperEdit" 可能是 BaseEditExercise 内部逻辑的一部分,而 ref="paperEdit" 则是 Vue 原生用于父组件操作子组件的桥梁。

$refs 的用法

设置 ref 属性 在模板中,通过 ref 属性为 DOM 元素或子组件设置唯一的标识符:

<template>
    <div>
        <input ref="myInput" type="text" />
        <MyComponent ref="myComponent" />
    </div>
</template>

访问引用 在 JavaScript 中,可以通过 this.$refs 来访问这些引用:

export default {
    methods: {
        focusInput() {
            // 访问 DOM 元素并操作
            this.$refs.myInput.focus();
        },
        callComponentMethod() {
            // 调用子组件的方法
            this.$refs.myComponent.someMethod();
        }
    }
};
⚠️ **GitHub.com Fallback** ⚠️