我尝试深入了解VUE的计算功能。
我知道,只有在与函数相关的值发生更改时,计算机才会运行。
所以我期望我编写的计算函数能很好地工作。但是,它仅在函数位于“方法”挂钩中时运行。
为什么在计算时不能使它发生?
我的代码如下。
-html-
<script src="https://npmcdn.com/vue/dist/vue.js"></script>
<div id="exercise">
<!-- 1) Show an alert when the Button gets clicked -->
<div>
<button @click='showalert'>Show Alert</button>
</div>
<!-- 2) Listen to the "keydown" event and store the value in a data property (hint: event.target.value gives you the value) -->
<div>
<input type="text" v-on:keyup='updatekey'>
<p>{{ value }}</p>
</div>
<!-- 3) Adjust the example from 2) to only fire if the "key down" is the ENTER key -->
<div>
<input type="text">
<p>{{ value }}</p>
</div>
</div>
<script src='./app.js'></script>
app.js
new Vue({
el: '#exercise',
data: {
value: ''
},
methods:{
showalert(){
alert('You just clicked')
},
},
computed:{
updatekey(e){
this.value=event.target.value
}
}
});
因为computed
包含properties
,它返回一个值,而不是偶数处理程序。事件处理程序是应该在methods
内部捕获的闭包。
查看Vue.js文档中的示例示例:
var vm = new Vue({
el: '#example',
data: {
message: 'Hello'
},
computed: {
// a computed getter
reversedMessage: function () {
// `this` points to the vm instance
return this.message.split('').reverse().join('')
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="example">
<p>Original message: "{{ message }}"</p>
<p>Computed reversed message: "{{ reversedMessage }}"</p>
</div>
这里,reversedMessage
的用法与DOM中的普通data
属性一样,但实际上与其他数据属性相关。
在您的情况下,updatekey
显然是处理程序,当触发事件时,需要进行一些更改或进行一些计算。