Vue 3 中定义组件常用方法

在Vue 3 中有多种定义组件的方法。从选项到组合再到类 API,情况大不相同

1、方式一:Options API

这是在 Vue 中声明组件的最常见方式。从版本 1 开始可用,您很可能已经熟悉它。一切都在对象内声明,数据在幕后由 Vue 响应。它不是那么灵活,因为它使用 mixin 来共享行为。

javascript 复制代码
<script>
import TheComponent from './components/TheComponent.vue'
import componentMixin from './mixins/componentMixin.js'

export default {
  name: 'OptionsAPI',
  components: {
    TheComponent,
    AsyncComponent: () => import('./components/AsyncComponent.vue'),
  },
  mixins: [componentMixin],
  props: {
    elements: {
      type: Array,
    },
    counter: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      object: {
        variable: true,
      },
    }
  },
  computed: {
    isEmpty() {
      return this.counter === 0
    },
  },
  watch: {
    counter() {
      console.log('Counter value changed')
    },
  },
  created() {
    console.log('Created hook called')
  },
  mounted() {
    console.log('Mounted hook called')
  },
  methods: {
    getParam(param) {
      return param
    },
    emitEvent() {
      this.$emit('event-name')
    },
  },
}
</script>
<template>
  <div class="wrapper">
    <TheComponent />
    <AsyncComponent v-if="object.variable" />
    <div class="static-class-name" :class="{ 'dynamic-class-name': object.variable }">
      Dynamic attributes example
    </div>
    <button @click="emitEvent">Emit event</button>
  </div>
</template>

<style lang="scss" scoped>
.wrapper {
  font-size: 20px;
}
</style>

方式二:Composition API

在 Vue 3 中引入了 Composition API。 目的是提供更灵活的 API 和更好的 TypeScript 支持。这种方法在很大程度上依赖于设置生命周期挂钩。

javascript 复制代码
<script>
import {
  ref,
  reactive,
  defineComponent,
  computed,
  watch,
} from 'vue'

import useMixin from './mixins/componentMixin.js'
import TheComponent from './components/TheComponent.vue'

export default defineComponent({
  name: 'CompositionAPI',
  components: {
    TheComponent,
    AsyncComponent: () => import('./components/AsyncComponent.vue'),
  },
  props: {
    elements: Array,
    counter: {
      type: Number,
      default: 0,
    },
  },
  setup(props, { emit }) {
    console.log('Equivalent to created hook')

    const enabled = ref(true)
    const object = reactive({ variable: false })

    const { mixinData, mixinMethod } = useMixin()

    const isEmpty = computed(() => {
      return props.counter === 0
    })

    watch(
      () => props.counter,
      () => {
        console.log('Counter value changed')
      }
    )

    function emitEvent() {
      emit('event-name')
    }
    function getParam(param) {
      return param
    }

    return {
      object,
      getParam,
      emitEvent,
      isEmpty
    }
  },
  mounted() {
    console.log('Mounted hook called')
  },
})
</script>

<template>
  <div class="wrapper">
    <TheComponent />
    <AsyncComponent v-if="object.variable" />
    <div class="static-class-name" :class="{ 'dynamic-class-name': object.variable }">
      Dynamic attributes example
    </div>
    <button @click="emitEvent">Emit event</button>
  </div>
</template>

<style scoped>
.wrapper {
  font-size: 20px;
}
</style>

使用这种混合方法需要大量样板代码,而且设置函数很快就会失控。在迁移到 Vue 3 时,这可能是一个很好的中间步骤,但是语法糖可以让一切变得更干净。

方式三:Script setup

在 Vue 3.2 中引入了一种更简洁的语法。通过在脚本元素中添加设置属性,脚本部分中的所有内容都会自动暴露给模板。通过这种方式可以删除很多样板文件。

javascript 复制代码
<script setup>
import {
  ref,
  reactive,
  defineAsyncComponent,
  computed,
  watch,
  onMounted,
} from "vue";

import useMixin from "./mixins/componentMixin.js";
import TheComponent from "./components/TheComponent.vue";
const AsyncComponent = defineAsyncComponent(() =>
  import("./components/AsyncComponent.vue")
);

console.log("Equivalent to created hook");
onMounted(() => {
  console.log("Mounted hook called");
});

const enabled = ref(true);
const object = reactive({ variable: false });

const props = defineProps({
  elements: Array,
  counter: {
    type: Number,
    default: 0,
  },
});

const { mixinData, mixinMethod } = useMixin();

const isEmpty = computed(() => {
  return props.counter === 0;
});

watch(() => props.counter, () => {
  console.log("Counter value changed");
});

const emit = defineEmits(["event-name"]);
function emitEvent() {
  emit("event-name");
}
function getParam(param) {
  return param;
}
</script>

<script>
export default {
  name: "ComponentVue3",
};
</script>

<template>
  <div class="wrapper">
    <TheComponent />
    <AsyncComponent v-if="object.variable" />
    <div
      class="static-class-name"
      :class="{ 'dynamic-class-name': object.variable }"
    >
      Dynamic attributes example
    </div>
    <button @click="emitEvent">Emit event</button>
  </div>
</template>

<style scoped>
.wrapper {
  font-size: 20px;
}
</style>
相关推荐
爷_4 小时前
字节跳动震撼开源Coze平台!手把手教你本地搭建AI智能体开发环境
前端·人工智能·后端
charlee445 小时前
行业思考:不是前端不行,是只会前端不行
前端·ai
Amodoro6 小时前
nuxt更改页面渲染的html,去除自定义属性、
前端·html·nuxt3·nuxt2·nuxtjs
Wcowin6 小时前
Mkdocs相关插件推荐(原创+合作)
前端·mkdocs
伍哥的传说7 小时前
CSS+JavaScript 禁用浏览器复制功能的几种方法
前端·javascript·css·vue.js·vue·css3·禁用浏览器复制
lichenyang4537 小时前
Axios封装以及添加拦截器
前端·javascript·react.js·typescript
Trust yourself2437 小时前
想把一个easyui的表格<th>改成下拉怎么做
前端·深度学习·easyui
苹果醋37 小时前
iview中实现点击表格单元格完成编辑和查看(span和input切换)
运维·vue.js·spring boot·nginx·课程设计
武昌库里写JAVA7 小时前
iView Table组件二次封装
vue.js·spring boot·毕业设计·layui·课程设计
三口吃掉你7 小时前
Web服务器(Tomcat、项目部署)
服务器·前端·tomcat