ref函数
主要用于定义简单数据类型,但是也可以定义复杂数据类型
1.1插槽只能绑定setup返回的对象
1.2默认的定义的数据都不是响应式数据,如果需要响应式数据需要引入ref函数,template需要自动解包
<script>
import { ref } from 'vue'
export default {
setup(){
setup(){
let counter = ref(999)
const increament = () =>{
counter.value++
}
const decreament = (){
counter.value--
}
//返回对象
return {
counter,
increament,
decreament
}
}
}
}
</script>
<script>
import { ref } from 'vue'
export default {
setup(){
setup(){
let counter = ref(999)
const increament = () =>{
counter.value++
}
const decreament = (){
counter.value--
}
//返回对象
return {
counter,
increament,
decreament
}
}
}
}
</script>
封装
counter,js
<script>
import { ref } from 'vue'
export default function userRef() {
let counter = ref(999)
const increamer = () => {
counter.value++
// console.log("counter.value")
}
const decreamer = () => {
counter.value--
}
return {
counter,
increamer,
decreamer
}
}
</script>
XXX.vue
<script>
import counter from './hooks/counter'
import userRef from './hooks/counter'
export default {
setup() {
//es6引入
const {counter, increamer,decreamer}=userRef()
return {
counter,
increamer,
decreamer
}
}
}
</script>
或者直接返回对象("..."展开运算符)
<script>
import counter from './hooks/counter'
import userRef from './hooks/counter'
export default {
setup() {
//es6引入
return {
...uerRef()
}
}
}
</script>
Reactive函数(掌握)
1.1主要用于定义复杂数据类型 ,(只能传入一个数组或对象)
1.2如果想为setup函数中定义的数据具有响应式特性,就可以使用reactive
1.3思考原理?
<script>
import{ reactive} from 'vue'
export default {
setup(){
const acount =reactive({
username:"XXXXXX",
password:"XXXXXX"
})
//动态改变数据
function empty(){
acount.username=""
acount.password=""
}
}
}
</script>
原理:当我们使用reactive函数处理我们的数据之后。数据再次被使用时就会进行依赖收集(与data函数的原理一样)