vue 创建公共可复用的JS方法
时间: 2023-01-28 20:18:47 浏览: 67
在 Vue 中,你可以在 Vue 实例的 methods 属性中添加公共方法。
例如:
```
new Vue({
el: '#app',
data: {
message: 'Hello Vue.js!'
},
methods: {
reverseMessage: function () {
this.message = this.message.split('').reverse().join('')
}
}
})
```
这样你就可以在模板中使用该方法了:
```
<template>
<div>
<p>{{ message }}</p>
<button v-on:click="reverseMessage">Reverse Message</button>
</div>
</template>
```
你也可以在组件中使用 methods,方法是可以被多个实例复用的。
例如:
```
Vue.component('my-component', {
template: '<p>{{ message }}</p>',
data: function () {
return {
message: 'Hello from my component!'
}
},
methods: {
reverseMessage: function () {
this.message = this.message.split('').reverse().join('')
}
}
})
```
然后你就可以在组件的模板中使用该方法了:
```
<template>
<div>
<my-component></my-component>
<button v-on:click="reverseMessage">Reverse Message</button>
</div>
</template>
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)