我正在使用 Vue.js,我想向我的组件 Map.vue 添加一个函数,因此当我单击按钮时,它会调用在同一文件中声明的函数:
<template>
<div>
<div class="google-map" :id="mapName">
</div>
<button >Do stuff</button>
</div>
</template>
我只看到了在 App.vue 中声明函数时的示例。如何在我的 Map.vue 文件中执行此操作?
最佳答案
事件
App.vue
和 Map.vue
都是组件,因此它们在“同一文件”( single file components ) 中调用函数(方法)时工作方式相同。
触发event添加 v-on:click="yourFunctionHere()"
,然后确保在脚本部分的 methods
对象中声明您的函数:
Map.vue
<template>
<div>
<div class="google-map" :id="mapName">
</div>
<button v-on:click="doStuff()">Do stuff</button>
</div>
</template>
<script>
export default {
methods: {
doStuff () {
alert('Did something!')
}
}
}
</script>
自定义事件
由于不太清楚子组件 Map.vue
是什么让您感到困惑(因为您了解父组件 App.vue
),也许您在问如何调用来自子 Map.vue
中的按钮的 App.vue
中的函数?
如果是这种情况,那么您需要使用custom events child 与家长的沟通:
Map.vue
<template>
<div>
<div class="google-map" :id="mapName">
</div>
<button v-on:click="doStuff()">Do stuff</button>
</div>
</template>
<script>
export default {
methods: {
doStuff () {
this.$emit('childStuff', 'some value from child')
}
}
}
</script>
App.vue
<template>
<div>
<Map v-on:childStuff="value => { parentStuff(value) }"></Map>
</div>
</template>
<script>
import Map from './components/Map'
export default {
components: {
Map
},
methods: {
parentStuff (value) {
alert(value)
}
}
}
</script>
关于javascript - Vue.js 向组件添加函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48305891/