首页 技术 正文
技术 2022年11月16日
0 收藏 432 点赞 3,969 浏览 1407 个字

需求:Vue 中, 我们可以像下面这样通过在 引号双花括号 内写 js 表达式去做一些简单运算, 这是可以的, 不过这样写是不直观的, 而且在 html夹杂 一些运算逻辑这种做法其实并不好. 最理想的情况是: html 只负责展示, 绑定的数据都是 赤裸裸变量, 而非 表达式 , 这样就会比较人性化. 想要达到这种效果可以有两种方法: computedmethods.

怎样理解 Vue 中的计算属性 computed 和 methods ?

1. 使用 methods 相当于是为这个 字符串倒序 的功能单独写了一个函数, 这个函数在 Vue 实例对象的 methods 属性中, 我们可以直接在 html 中使用它, 注意这里要带括号: inputValueReverse()

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<title>Vue Test</title>
</head>
<body>
<div id="app">
<input type="text" v-model:value="inputValue" />
<span>{{ inputValueReverse() }}</span>
</div>
<script>
var vApp = new Vue({
el: "#app",
data: {
inputValue: ''
},
methods: {
inputValueReverse: function () {
return this.inputValue.split('').reverse().join('');
}
}
})
</script>
</body>
</html>

2. 使用 computed, 其效果跟使用 methods 类似, 只是 作用原理 不同, 计算属性 computed 的执行是 惰性 的, 只有它所 依赖缓存 的变量发生了改变, 它才会重新执行, 这是它和 methods 的本质区别, methods 是只要发生 重新渲染 就会执行, 而 computed 不会. 所以我们可以认为 使用 computed 时性能会更好, 但 使用 methods 会更灵活, 所以具体使用哪一个得视情况而定. 另外需要注意的一点是 使用 computed 时是 不需要加括号 的, 如下所示, 它可以像一般变量一样 赤裸裸 地绑定, 而且性能也好, 可以说是很 nice 了.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<title>Vue Test</title>
</head>
<body>
<div id="app">
<input type="text" v-model:value="inputValue" />
<span>{{ inputValueReverse }}</span>
</div>
<script>
var vApp = new Vue({
el: "#app",
data: {
inputValue: ''
},
computed: {
// 计算属性的 getter
inputValueReverse: function () {
return this.inputValue.split('').reverse().join('');
}
}
})
</script>
</body>
</html>
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,078
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,553
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,402
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,177
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,814
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,898