vue.js 暴露方法_Vue.js方法

vue.js 暴露方法



什么是Vue.js方法 (What are Vue.js methods)

A Vue method is a function associated with the Vue instance.

Vue方法是与Vue实例关联的函数。

Methods are defined inside the methods property:

方法在methods属性内定义:

new Vue({
  methods: {
    handleClick: function() {
      alert('test')
    }
  }
})

or in the case of Single File Components:

或对于单个文件组件:

<script>
export default {
  methods: {
    handleClick: function() {
      alert('test')
    }
  }
}
</script>

Methods are especially useful when you need to perform an action and you attach a v-on directive on an element to handle events. Like this one, which calls handleClick when the element is clicked:

当您需要执行操作并将v-on指令附加到元素上以处理事件时,方法特别有用。 像这样,在单击元素时调用handleClick

<template>
  <a @click="handleClick">Click me!</a>
</template>

将参数传递给Vue.js方法 (Pass parameters to Vue.js methods)

Methods can accept parameters.

方法可以接受参数。

In this case, you just pass the parameter in the template, and you

在这种情况下,您只需在模板中传递参数,然后

<template>
  <a @click="handleClick('something')">Click me!</a>
</template>
new Vue({
  methods: {
    handleClick: function(text) {
      alert(text)
    }
  }
})

or in the case of Single File Components:

或对于单个文件组件:

<script>
export default {
  methods: {
    handleClick: function(text) {
      alert(text)
    }
  }
}
</script>

如何从方法访问数据 (How to access data from a method)

You can access any of the data properties of the Vue component by using this.propertyName:

您可以使用this.propertyName来访问Vue组件的任何数据属性:

<template>
  <a @click="handleClick()">Click me!</a>
</template>

<script>
export default {
  data() {
    return {
      name: 'Flavio'
    }
  },
  methods: {
    handleClick: function() {
      console.log(this.name)
    }
  }
}
</script>

We don’t have to use this.data.name, just this.name. Vue does provide a transparent binding for us. Using this.data.name will raise an error.

我们不必使用this.data.name ,而只需使用this.name 。 Vue确实为我们提供了透明的绑定。 使用this.data.name将引发错误。

As you saw before in the events description, methods are closely interlinked to events, because they are used as event handlers. Every time an event occurs, that method is called.

如您在事件描述中之前所看到的,方法与事件紧密关联,因为它们被用作事件处理程序。 每次事件发生时,都会调用该方法。

翻译自: https://flaviocopes.com/vue-methods/

vue.js 暴露方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值