Vue3 coderwhy 15p 混入mixin和composition API

546 阅读1分钟

混入mixin

  1. 对相同的js代码进行抽取,公共代码抽取、共享
  2. 使用方法
- export default xxMixin = {//在js文件里
-     data(){
-         return{
-             obj: '123'
-         }
-     },
-     created(){
-         
-     }
- }
- 组件中使用混入
- import { demoMixin } from './xxMixin';
- export default {
-     mounted(){},// 同级目录
-     mixin: [xxMixin],//一般是数组,
- }
- 
  1. mixin里,data数据冲突会保留组件里的
  2. mixin里,钩子函数重复是合并的
  3. 全局混入
- 在main.js里
- const app = createApp(App);
- app.mixin({
-      data(){
-          return{}
-      }
- })

Vue3 composition API

  1. Vue2 option API 代码非常碎片化,难以阅读,所以有composition API
  2. setup函数有参数props,和context上下文
  3. setup函数无法使用this.
- props:[‘abc’],
- setup( props,context ){
-     
- } 
- //第二种写法
- setup( props,{ attr,slots,emit } ){
-     
- } 
  1. context有三个属性

    • attrs: 所有非prop的attribute
    • slots: 父组件传递过来的插槽
    • emit: 用于向父组件发送事件
  2. setup的返回值相当于定义data setup( props, { attrs,slots,emit }) { const addBtn = () => {} return{ time: xx, addBtn, } }

  3. reactive 响应式API

- 导入import { reactive } from 'vue';
- 在setup里使用
- const state = reactive({
-     counter: 100
- })
- 
- return{
-     state,
- }
- 在模板里使用
- {{ state.counter }}
  1. ref API 可响应式的引用(依旧先导入)
- const counter = ref(100)
- counter.value++;
- 在模板中
- {{ counter }} //自动解包
  1. readonly API 只读 const info = readonly( info2 )