<div id="example">
{{ message.split('').reverse().join('') }}
</div>
>
p>Original message: "{{ message }}">Computed reversed message: "{{ reversedMessage }}">
>
var vm = new Vue({
el: '#example',data: {
message: 'Hello'
},computed: {
// 计算属性的 getter
reversedMessage: function () {
`this` 指向 vm 实例
return this.message.split('').reverse().join('')
}
}
})
Original message: "Hello"
Computed reversed message: "olleH"
console.log(vm.reversedMessage) => 'olleH'
vm.message = 'Goodbye'
console.log(vm.reversedMessage) => 'eybdooG'
<p>Reversed message: "{{ reversedMessage() }}"</p>
在组件中
methods: {
reversedMessage: () {
)
}
}
computed: {
now: return Date.now()
}
}
="demo">{{ fullName }} Vue({
el: '#demo''Bar' (val) {
this.fullName = val + ' ' + this.lastName
},lastName: this.fullName = this.firstName + ' ' + val
}
}
})
this.firstName + ' ' + .lastName
}
}
})
...
computed: {
fullName: {
getter
get: setter
set: (newValue) {
var names = newValue.split(' ')
this.firstName = names[0]
this.lastName = names[names.length - 1]
}
}
}
...
="watch-example"
Ask a yes/no question:
input v-model="question">{{ answer }}>
<!-- 因为 AJAX 库和通用工具的生态已经相当丰富,Vue 核心代码没有重复 -->
<!-- 提供这些功能以保持精简。这也可以让你自由选择自己更熟悉的工具。 -->
<script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.13.1/lodash.min.js"></script>
<script>
var watchExampleVM = Vue({
el: '#watch-example''I cannot give you an answer until you ask a question!' 如果 `question` 发生改变,这个函数就会运行
question: (newQuestion) {
this.answer = 'Waiting for you to stop typing...'
.getAnswer()
}
},methods: {
`_.debounce` 是一个通过 Lodash 限制操作频率的函数。
在这个例子中,我们希望限制访问 yesno.wtf/api 的频率
AJAX 请求直到用户输入完毕才会发出。想要了解更多关于
`_.debounce` 函数 (及其近亲 `_.throttle`) 的知识,
请参考:https://lodash.com/docs#debounce
getAnswer: _.debounce(
() {
if (this.question.indexOf('?') === -1) {
this.answer = 'Questions usually contain a question mark. ;-)'
}
this.answer = 'Thinking...'
axios.get('https://yesno.wtf/api')
.then( (response) {
vm.answer = _.capitalize(response.data.answer)
})
.catch( (error) {
vm.answer = 'Error! Could not reach the API. ' + error
})
},1)"> 这是我们为判定用户停止输入等待的毫秒数
500
)
}
})
</script>
键路径
vm.$watch('a.b.c', (newVal,oldVal) {
做点什么
})
="app">
type="text" v-model="a" />
="b" />
>
函数
Vue({
el: '#app''文本2'this.a + .b
},oldVal) {
console.log(newVal,oldVal);
}
)
var unwatch = vm.$watch('a' 之后取消观察
unwatch()
vm.$watch('someObject'true
})
vm.someObject.nestedValue = 123
callback is fired
vm.$watch('a'
})
立即以 `a` 的当前值触发回调