关于vue.js:关于vue3-compositionAPI

28次阅读

共计 1998 个字符,预计需要花费 5 分钟才能阅读完成。

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

正文完
 0