setup函数的参数props,context
setup(props, context) {
},
props:一般通过父组件传递过来的属性会放到props对象里,使用时可直接通过props获取
context:里面包含三个属性
attrs:所有非prop的attribute;
slots:父组件传递过来的的插槽;
emit:当我们组件内部emit时会用到
setup不可使用this!
官方文档这里有写
ref的使用
将一个原始数据类型(primitive data type)转换成一个带有响应式特性的数据类型,原始数据类型共有7个,分别是:
**String
Number
BigInt
Boolean
Symbol
Null
Undefined**
ref会浅层解包,在templete上直接用{{test}}就好了
setup() {
let test = ref(0)
let tobj = ref({a: 1});
// test.value = 1;
const testFun = () => {
test.value++;
tobj.a.vaue = 'b';
console.log(tobj.a)
};
return {
tobj,
robj,
test,
testFun,
}
},
假设我们在定义了用ref定义了tobj是对象,当我们在testFun改变值时,会报错
reactive的使用
reactive (等价于Vue2中的Vue.observable() )来赋予对象(Object) 响应式的特性的。
假设我们这么写
<template>
<div class="home">
<h1>{{a}}</h1>
<button @click="handleClick">1</button>
</div>
</template>
<script>
import { defineComponent } from 'vue';
import { ref, reactive } from 'vue'
export default defineComponent({
setup() {
let robj = reactive({
a: 'a',
handleClick: () => {
robj.a = 'c';
console.log(robj);
},
});
return { ...robj }
},
});
</script>
这时候我们发现,页面并没有发生变化!事实上,这样写没有效果的原因就在于一个响应型对象(reactive object) 一旦被销毁或展开,其响应式特性(reactivity)就会丢失。通过检查我们可以知道,虽然robj.a的值确实发生了变化,但robj.ae的类型只是一个普通的字符串(String) ,并不具有响应式特性(reactivity),故而页面也没有随着其值的变化而重新渲染。
我们可以改为
<template>
<div class="home">
<h1>{{robj.a}}</h1>
<button @click="robj.handleClick">1</button>
</div>
</template>
<script>
import { defineComponent } from 'vue';
import { ref, reactive } from 'vue'
export default defineComponent({
setup() {
let robj = reactive({
a: 'a',
handleClick: () => {
robj.a = 'c';
console.log(robj);
},
});
return { robj }
},
});
</script>
这样页面就能随着值的变化而进行渲染,但是这么代码有点过于复杂,这时候就引出了toRefs。
toRefs的使用
Vue3提供了一个新的API:toRefs,它可以将一个响应型对象(reactive object) 转化为普通对象(plain object),同时又把该对象中的每一个属性转化成对应的响应式属性(ref)。
<template>
<div class="home">
<h1>{{a}}</h1>
<button @click="handleClick">1</button>
</div>
</template>
<script>
import { defineComponent } from 'vue';
import { ref, reactive } from 'vue'
export default defineComponent({
setup() {
let robj = reactive({
a: 'a',
handleClick: () => {
robj.a = 'c';
console.log(robj);
},
});
const robjAsRefs = toRefs(robj);
return { ...robjAsRefs }
},
});
</script>
最后总结成表格方便大家忘记特性的时候查阅
类型 | 是否触发页面改变 | 是否可以解构 |
---|---|---|
ref | 是 | 否 |
reactive | 是 | 否 |
toRef | 否 | 否 |
toRefs | 否 | 是 |
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。