我最近一直在學習 Vue3。我想動態添加組件,父組件可以監聽添加的子組件的事件。為了明確我想要做什么,我撰寫了以下代碼。當滑鼠移到任何按鈕上時,我希望添加一個新按鈕。但實際上只有第一個按鈕觸發了 hello 函式,也就是說第"v-on:addButton": hello7 行的代碼App.vue不起作用。我想知道如何修改代碼以滿足我的要求,或者是否有另一種簡單的方法來實作此功能。
孩子components/Hello.vue
<script setup lang="ts">
defineProps(['text'])
defineEmits(['addButton'])
</script>
<template>
<button @mouseenter="$emit('addButton')">{{text}}</button>
</template>
父親App.vue
<script setup>
import {createApp} from 'vue'
import Hello from './components/Hello.vue'
let cnt = 0
function hello() {
console.log('you enter a button')
const app = createApp(Hello, {"text": String(cnt ), "v-on:addButton": hello})
const newNode = document.createElement('div')
document.getElementById("rootDiv").append(newNode)
app.mount(newNode)
}
</script>
<template>
<div id="rootDiv">
<Hello text="0" v-on:addButton="hello"/>
</div>
</template>
uj5u.com熱心網友回復:
在大多數情況下直接操作 DOM 不適用于 Vue,因為您將失去反應性和其他系結內容,另一種方法是使用cnt變數來使用v-for指令渲染組件;:
<script setup>
import {ref} from 'vue'
import Hello from './components/Hello.vue'
let cnt = ref(0)
function addBtn() {
cnt.value
}
</script>
<template>
<div id="rootDiv">
<Hello v-for="i in cnt" :text="i" v-on:addButton="addBtn"/>
</div>
</template>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/494000.html
標籤:javascript Vue.js
上一篇:如何使用承諾取消睡眠?
