原来组件中使用computed是直接使用:
computed() {
// 内容
}
但是,setup()函数中使用computed计算属性时,
需要先从 Vue对象中解构赋值,获得 computed:
const { computed } = Vue
computed() 中可以传 方法,也可以传对象
代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>计算属性computed</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
</body>
<script>
/* const app = Vue.createApp({
setup() {
const { ref, computed } = Vue
const count = ref(20)
const handleClick = () => {
count.value += 1
}
const countTen = computed(() => {
return count.value + 10
})
return { count, countTen, handleClick }
},
template: `<div @click="handleClick">{{count}}--{{countTen}}</div> `
}) */
/* const app = Vue.createApp({
setup() {
const { ref, computed } = Vue
const count = ref(20)
const handleClick = () => {
count.value += 1
}
let countTen = computed({
get: () => {
return count.value + 10
},
set: (param) => {
count.value = param - 2
}
})
setTimeout(() => {
countTen.value = 10
}, 3000)
return { count, countTen, handleClick }
},
template: `<div @click="handleClick">{{count}}--{{countTen}}</div> `
}) */
const app = Vue.createApp({
setup() {
const { reactive, computed } = Vue
const countObj = reactive({count: 10})
const handleClick = () => {
countObj.count += 1
}
let countTen = computed({
get: () => {
return countObj.count + 10
},
set: (param) => {
countObj.count = param - 2
}
})
// 设置一个定时器,3秒后改变值大小
setTimeout(() => {
countTen.value = 10
}, 3000)
return { countObj, countTen, handleClick }
},
template: `<div @click="handleClick">{{countObj.count}}--{{countTen}}</div> `
})
const vm = app.mount('#root')
</script>
</html>