javascript Vue.js 给组件添加函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48305891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:57:47  来源:igfitidea点击:

Vue.js add function to a component

javascriptvue.jsvuejs2vue-component

提问by Rémy Kaloustian

I am using Vue.js and I would like to add a function to my component, Map.vue, so when I click the button it calls a function declared in the same file :

我正在使用 Vue.js 并且我想向我的组件 Map.vue 添加一个函数,因此当我单击按钮时,它会调用在同一文件中声明的函数:

<template>
  <div>
    <div class="google-map" :id="mapName">
    </div>
    <button >Do stuff</button>  
  </div>
</template>

I have only seen examples when the function is declared in the App.vue. How do you do that in my Map.vue file ?

我只见过在 App.vue 中声明函数的例子。你如何在我的 Map.vue 文件中做到这一点?

回答by prograhammer

Events

活动

Both App.vueand Map.vueare components so they work the same for calling functions (methods) "in the same file" (single file components).

双方App.vueMap.vue因此他们的工作一样调用函数(方法)“在同一个文件”(是组件单个文件组件)。

Trigger an eventby adding v-on:click="yourFunctionHere()"and then make sure to declare your function in the methodsobject of the script section:

通过添加触发事件v-on:click="yourFunctionHere()",然后确保methods在脚本部分的对象中声明您的函数:

Map.vue

地图.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>

Custom Events

自定义事件

Since it's a little unclear what confused you about the child component Map.vue(since you understand the parent App.vue), perhaps you are asking how to call a function in App.vuefrom a button in the child Map.vue?

由于有点不清楚是什么让您对子组件感到困惑Map.vue(因为您了解父组件App.vue),也许您正在询问如何App.vue从子组件中的按钮调用函数Map.vue

If that's the case, then you need to use custom eventsfor child to parent communication:

如果是这种情况,那么您需要使用自定义事件进行子级到父级的通信:

Map.vue

地图.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>