vue.js - 通过自定义 Vue 组件中的方法访问实例
问题描述
我正在尝试通过自定义注册的 Vue 组件中的触发方法访问实例方法/数据。
下面是一个基本示例:
Vue.component('example-component', {
template: `<div>
<h2>Count: {{count}}</h2>
<button class="btn btn-primary" v-on:click="increment()">Increment</button>
</div>`,
data: () => {
return {
count: 0
}
},
methods: {
increment: () => {
console.log("Click!");
console.log("Current count: ", this.count);
this.count++;
console.log("New count: ", this.count);
},
decrement: () => {
// other function
}
},
mounted: () => {
console.log("Example component mounted!");
}
});
结果:
Example component mounted!
Click!
Current count: undefined
New count: NaN
您可能会注意到属性“count”已在组件挂载期间加载,并且在 HTML 中可用/呈现。方法“increment()”也已被触发。然而,'this.count' 似乎是无法访问的,就像其他可能的方法(例如'this.decrement()')会抛出 TypeError this.decrement is not a function。
如果这种方法是可能的,有什么建议吗?
PS。我知道通过 .vue 文件注册表的默认方法,例如:
Vue.component('example-component', require('./components/ExampleComponent.vue').default);
解决方案
推荐阅读
- php - 在 PHP 中计算日期之间的绝对差异
- php - 如何在同一域名下的同一 nginx 服务器上运行 angular 和 wordpress 项目
- android - 错误:找不到 Gradle DSL 方法:'freeImplementation()'
- python - 如何在 dockerized django 中重新加载 python 代码?
- r - 根据特定属性对 igraph 进行子图化以仅包含前 N 个“最大”节点
- xml - 如何定义 avro 模式以在 Nifi 上使用 ConvertRecord 获取 xml 属性?
- mysql - 我需要替换字符串的字符 \\ 并使用 JSON_EXTRACT 读取
- windows - 同时无声地从一个批处理文件运行多个 .exe 文件
- razorpay - 如何使用android在后端生成razorpay订单ID?
- javascript - 如何在 d3.js v5 中设置初始缩放