我在我的应用程序/vue 中初始化了一个简单的方法“updateTotal”:
// start app
new Vue({
el: '#app2',
data: {
showModal1: false,
showModal2: false,
total : 0
},
methods: {
updateTotal: function (num) {
this.total = this.total + num
}
}
})
当我通过 app2 部分的 HTML 代码中的一个按钮调用此方法时,没问题(文本“total”已更新)。
当我从隐藏在页面加载时的 div 部分调用此方法时(它是一个模式,带有 vue.js“转换”系统),我有这个错误: 属性或方法“updateTotal”未在实例上定义,但在渲染期间被引用。通过初始化该属性,确保该属性在数据选项中或对于基于类的组件是 react 性的。
这个模式/转换的代码(它在 app2 div 中)是:
<!-- template for the modal component SERVICES-->
<script type="text/x-template" id="modal2-template">
<transition name="modal2">
<div class="modal-mask">
<div class="modal-wrapper">
<div class="modal-container">
<div class="modal-header">
<slot name="header">
Header
</slot>
</div>
<div class="modal-body">
<!-- LISTE SERVICES -->
<div>
<div>
<div class="control">
<label class="radio">
<input type="radio" name="service1" v-on:click="updateTotal(10)">
Oui
</label>
<label class="radio">
<input type="radio" name="service1" checked v-on:click="updateTotal(-10)">
Non
</label>
</div>
</div>
<div>
<div class="control">
<label class="radio">
<input type="radio" name="service2" v-on:click="updateTotal(20)">
Oui
</label>
<label class="radio">
<input type="radio" name="service2" checked v-on:click="updateTotal(-20)">
Non
</label>
</div>
</div>
</div>
<!-- LISTE SERVICES -->
</div>
<div class="modal-footer">
<slot name="footer">
default footer
<button class="modal-default-button" @click="$emit('close')">
OK
</button>
</slot>
</div>
</div>
</div>
</div>
</transition>
</script>
我该怎么做才能从这个模态/过渡 div 调用这个方法?
谢谢!
MAMP MySQL PHP5
最佳答案
出现此问题是因为您尝试从不同组件的模板中调用 updateTotal()
。
template
中的上下文始终是组件本身(this
)。由于 updateTotal()
方法未在此组件中定义,因此您无法调用它。
有几种解决方法,但我认为其中两种是最干净的:
对于简单的项目/应用程序:发出触发父级方法的事件(例如您的
close
事件)对于更复杂的应用程序:使用 Vuex 的共享状态并使您的方法成为一个
action
关于vue.js - 在最初隐藏的模式中调用方法(转换),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57816746/