用 vue methods方法写
时间: 2024-01-29 20:03:28 浏览: 26
Vue 的 methods 是一个对象,可以在其中定义一些方法,以便在组件中调用。下面是一个例子:
```html
<template>
<div>
<button @click="sayHello">Say Hello</button>
</div>
</template>
<script>
export default {
name: 'MyComponent',
methods: {
sayHello() {
console.log('Hello!');
}
}
}
</script>
```
在上面的代码中,我们在 methods 中定义了一个名为 sayHello 的方法,当点击按钮时,该方法会在控制台中输出 "Hello!"。
在组件中,我们可以通过在模板中使用 `@click` 指令来调用该方法。指令 `@click` 相当于 `v-on:click`,用于绑定点击事件。当用户点击按钮时,该指令会触发 `sayHello` 方法。
你可以在 methods 中定义任意数量的方法,这些方法都可以在组件中调用。例如:
```html
<template>
<div>
<button @click="incrementCount">Increment</button>
<p>Count: {{ count }}</p>
</div>
</template>
<script>
export default {
name: 'MyComponent',
data() {
return {
count: 0
}
},
methods: {
incrementCount() {
this.count++;
}
}
}
</script>
```
在上面的代码中,我们定义了一个名为 `incrementCount` 的方法,该方法每次被调用时会将 `count` 属性增加1。在模板中,我们使用 `{{ count }}` 来显示当前的计数值。当用户点击 "Increment" 按钮时,该方法会被调用,从而更新计数值并重新渲染组件。
相关推荐
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)