Vue中的计算属性和方法属性

1、计算属性 computed

模版中可以使用表达式

<div id="example">
{{ message.split('').reverse().join('') }}
</div>

但是模版中的表达式太长,逻辑稍微复杂,应该使用计算属性

例如:

<div id="example">
<p>Original message: "{{ message }}"</p>
<p>Computed reversed message: "{{ reversedMessage }}"</p>
</div>
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('')
}
}
})

2、方法属性 methods

我们可以利用methods 来达到相同的目的

<p>Reversed message: "{{ reverseMessage() }}"</p>
// in component
methods: {
reverseMessage: function () {
return this.message.split('').reverse().join('')
}
}
计算属性和方法属性的不同之处:计算属性是基于它的依赖缓存的。计算属性只有在它的相关依赖发生改变时才会重新取值。这就意味着只要message没有发生改变,多次访问 reversedMessage计算属性会立即返回之前的计算结果,而不必再次执行函数。而methods在每次重新渲染的时候,调用总会执行。

由于 Date.now() 不是响应式依赖,所以下面的计算属性不会更新。

computed: {
now: function () {
return Date.now()
}
}

3、watch 属性

watch 用于观察Vue实例上的数据变动。当一些数据要根据其它数据变化时,$watch 可以使用。但是使用 computed更好用

<div id="demo">{{ fullName }}</div>
var vm = new Vue({
el: '#demo',
data: {
firstName: 'Foo',
lastName: 'Bar',
fullName: 'Foo Bar'
},
watch: {
firstName: function (val) {
this.fullName = val + ' ' + this.lastName
},
lastName: function (val) {
this.fullName = this.firstName + ' ' + val
}
}
})

使用computed

var vm = new Vue({
el: '#demo',
data: {
firstName: 'Foo',
lastName: 'Bar'
},
computed: {
fullName: function () {
return this.firstName + ' ' + this.lastName
}
}
})

4、setter

计算属性默认只有getter,不过可以在需要时自定义一个setter

// ...
computed: {
fullName: {
// getter
get: function () {
return this.firstName + ' ' + this.lastName
},
// setter
set: function (newValue) {
var names = newValue.split(' ')
this.firstName = names[0]
this.lastName = names[names.length - 1]
}
}
}
// ...

运行 vm.fullName = "Jarvis", setter会被调用, vm.firstName 和 vm.lastName 也会被更新.

5、运用watch实现一个观察器

当你想要在数据变化响应时,执行异步操作或昂贵操作时,很有用。

<div id="watch-example">
<p>
Ask a yes/no question:
<input v-model="question">
</p>
<p>{{ answer }}</p>
</div>
<!-- Since there is already a rich ecosystem of ajax libraries    -->
<!-- and collections of general-purpose utility methods, Vue core -->
<!-- is able to remain small by not reinventing them. This also -->
<!-- gives you the freedom to just use what you're familiar with. -->
<script src="https://unpkg.com/axios@0.12.0/dist/axios.min.js"></script>
<script src="https://unpkg.com/lodash@4.13.1/lodash.min.js"></script>
<script>
var watchExampleVM = new Vue({
el: '#watch-example',
data: {
question: '',
answer: 'I cannot give you an answer until you ask a question!'
},
watch: {
// 如果 question 发生改变,这个函数就会运行
question: function (newQuestion) {
this.answer = 'Waiting for you to stop typing...'
this.getAnswer()
}
},
methods: {
// _.debounce 是一个通过 lodash 限制操作频率的函数。
// 在这个例子中,我们希望限制访问yesno.wtf/api的频率
// ajax请求直到用户输入完毕才会发出
// 学习更多关于 _.debounce function (and its cousin
// _.throttle), 参考: https://lodash.com/docs#debounce
getAnswer: _.debounce(
function () {
var vm = this
if (this.question.indexOf('?') === -1) {
vm.answer = 'Questions usually contain a question mark. ;-)'
return
}
vm.answer = 'Thinking...'
axios.get('https://yesno.wtf/api')
.then(function (response) {
vm.answer = _.capitalize(response.data.answer)
})
.catch(function (error) {
vm.answer = 'Error! Could not reach the API. ' + error
})
},
// 这是我们为用户停止输入等待的毫秒数
500
)
}
})
</script>

参考VUE官网

Vue中computed,methods 和watch的更多相关文章

  1. vue中computed(计算属性)和watch在实现父子组件props同步时的实际区分

    vue中computed和watch的对比是一个很有意思的话题. 看过官网教程以后,我们往往更倾向多使用computed.computed优点很多,却在某些时候不太适用. 今天我们就稍微讨论一下,当我 ...

  2. Vue中computed分析

    Vue中computed分析 在Vue中computed是计算属性,其会根据所依赖的数据动态显示新的计算结果,虽然使用{{}}模板内的表达式非常便利,但是设计它们的初衷是用于简单运算的,在模板中放入太 ...

  3. Vue基础系列(二)——Vue中的methods属性

      写在前面的话: 文章是个人学习过程中的总结,为方便以后回头在学习. 文章中会参考官方文档和其他的一些文章,示例均为亲自编写和实践,若有写的不对的地方欢迎大家指出. 作者简介: 一个不知名的前端开发 ...

  4. Vue中computed和watch的区别

    在vue中computed和watch的真正区别是:computed产生于它的依赖,而watch产生于它的依赖的变化.只要依赖存在,我们就能访问到其对应的computed属性:但只有依赖发生了改变,我 ...

  5. vue中computed的作用以及用法

    在vue中computed是计算属性,主要作用是把数据存储到内存中,减少不必要的请求,还可以利用computed给子组件的data赋值. 参考地址:https://www.jianshu.com/p/ ...

  6. Vue中的methods、watch、computed

    看到这个标题就知道这篇文章接下来要讲的内容,我们在使用vue的时候methods.watch.computed这三个特性一定经常使用,因为它们是非常的有用,但是没有彻底的理解它们的区别和各自的使用场景 ...

  7. vue中computed与watch的异同

    一.computed 和 watch   都可以观察页面的数据变化.当处理页面的数据变化时,我们有时候很容易滥用watch. 而通常更好的办法是使用computed属性,而不是命令是的watch回调. ...

  8. Vue中computed与method的区别

    转载于:https://segmentfault.com/a/1190000014478664?utm_source=tag-newest 1.computed区别于method的两个核心 在官方文档 ...

  9. vue中computed计算属性与methods对象中的this指针

    this 指针问题 methods与computed中的this指针 应该指向的是它们自己,可是为什么this指针却可以访问data对象中的成员呢? 因为new Vue对象实例化后data中的成员和c ...

随机推荐

  1. iOS实现图片裁剪功能,基于TKImageView完善与讲解

    1.功能需求:需要实现图片区域裁剪功能. 2.效果图:     3.实现原理:本来想自己实现的,刚好看到一个比较好的库:TKImageView,下载好研究了下,发现基本都能满足我的需求,而且封装的也比 ...

  2. Linux下终端录制工具-asciinema

    1. 官网 https://asciinema.org/ 2. 功能 录音 录制终端命令 上传到多种位置 3. 使用方法 sudo yum install asciinema # 安装 asciine ...

  3. Android研发中对String的思考(源代码分析)

    1.经常使用创建方式思考: String text = "this is a test text "; 上面这一句话实际上是运行了三件事  1.声明变量 String text; ...

  4. Cmake find_package 需要指定具体的so

    需要使用cmake的find_package将boost库添加到项目中,通过cmake --help-module FindBoost 可以查看cmake引入Boost的帮助信息: 可以看到,Boot ...

  5. atom汉化

    Atom 是 Github 专门为程序员推出的一个跨平台文本编辑器. 推荐一下 Atom官方网站https://atom.io/ GitHub 以后肯定会通过官方模块把 Atom 和 GitHub 进 ...

  6. Git入门到高级系列1-git安装与基础命令

    视频课程地址 腾讯课堂 为什么要进行项目文件的版本管理 代码备份和恢复 团队开发和协作流程 项目分支管理和备份 git 是什么? git是一个分布式的版本控制软件.版本控制是一种记录一个或若干文件内容 ...

  7. 强化学习-时序差分算法(TD)和SARAS法

    1. 前言 我们前面介绍了第一个Model Free的模型蒙特卡洛算法.蒙特卡罗法在估计价值时使用了完整序列的长期回报.而且蒙特卡洛法有较大的方差,模型不是很稳定.本节我们介绍时序差分法,时序差分法不 ...

  8. 推荐使用@Resource,不推荐使用@Autowired

    @Autowired 默认根据ByType, 当一个类有两个对象的时候,会报错. @Resource 默认是ByName,可以精准的找到<bean>的配置项. jar包推送,应该级联推送: ...

  9. find ctime 加减n时间范围

    看下atime的时间解释:-atime n File was last accessed n*24 hours ago. When find figures out how many 24-hour ...

  10. 关系数据库(RDBMS)小记

    关系数据库三个范式 三个范式: 第一范式(1NF):数据表中的每一列(每个字段)必须是不可拆分的最小单元,也就是确保每一列的原子性 这里说的不可拆分通常是放在业务背景下而言的,是否可拆分视业务需求而定 ...