vue 正在不断发展,目前在版本 3 中有多种定义组件的方法。从选项到组合再到类 api,情况大不相同,如果您刚刚开始,可能会感到困惑。让我们定义一个简单的组件并使用所有可用的方法重构它。
这是在 Vue 中声明组件的最常见方式。从版本 1 开始可用,您很可能已经熟悉它。一切都在对象内声明,数据在幕后由 Vue 响应。它不是那么灵活,因为它使用 mixin 来共享行为。
<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>经过多次讨论、来自社区的反馈,以及令人惊讶的是,在这个 RFC中,有很多戏剧性的内容,在 Vue 3 中引入了 Composition API 。动机是提供更灵活的 API 和更好的 TypeScript 支持。这种方法在很大程度上依赖于设置生命周期挂钩。
<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 时,这可能是一个很好的中间步骤,但是语法糖可以让一切变得更干净。
在 Vue 3.2 中引入了一种更简洁的语法。通过在脚本元素中添加设置属性,脚本部分中的所有内容都会自动暴露给模板。通过这种方式可以删除很多样板文件。
<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>这是非常有争议的,被删除了!这使得脚本设置成为本文的明确答案。(26/1/2023 更新)
script setup以下代码段中演示的内容存在问题。
<script setup>
import { ref, computed } from 'vue'
const counter = ref(0)
counter.value++
function increase() {
  counter.value++
}
const double = computed(() => {
  return counter.value * 2
})
</script>
<template>
  <div class="wrapper">
    <button @click="increase">Increase</button>
    {{ counter }}
    {{ double }}
  </div>
</template>正如您所注意到的,访问响应式计数器感觉.value不自然,并且是混淆和错误输入的常见来源。有一个实验性解决方案利用编译时转换来解决此问题。反应性转换是一个可选的内置步骤,它会自动添加此后缀并使代码看起来更清晰。
<script setup>
import { computed } from 'vue'
let counter = $ref(0)
counter++
function increase() {
  counter++
}
const double = computed(() => {
  return counter * 2
})
</script>
<template>
  <div class="wrapper">
    <button @click="increase">Increase</button>
    {{ counter }}
    {{ double }}
  </div>
</template>$ref需要构建步骤,但无需.value访问变量。启用后它在全球范围内可用。
类 API 已经可用很长时间了。通常与 Typescript 搭配使用是 Vue 2 的可靠选择,并且被认真考虑为默认的 Vue 3 语法。但经过多次长时间的讨论后,它被放弃了,取而代之的是 Composition API。它在 Vue 3 中可用,但工具严重缺乏,官方建议远离它。无论如何,如果您真的喜欢使用类,您的组件将看起来像这样。
<script lang="ts">
import { Options, Vue } from 'vue-class-component';
  
import AnotherComponent from './components/AnotherComponent.vue'  
  
@Options({
  components: {
    AnotherComponent
  }
})
export default class Counter extends Vue {
  counter = 0;
  
  get double(): number {
    return this.counter * 2;
  }
  increase(): void {
    this.quantity++;
  }
}
</script>
<template>
  <div class="wrapper">
    <button @click="increase">Increase</button>
    {{ counter }}
    {{ double }}
  </div>
</template>那哪个最好呢?这取决于典型的反应,尽管在这种情况下并非如此。从 Vue 2 迁移时,选项和类 API 可以用作中间步骤,但它们不应该是您的首选。如果您没有构建阶段,组合 API 设置是唯一的选择,但由于大多数项目都是使用 webpack 或 Vite 生成的,因此使用脚本设置既是可能的,也是鼓励的,因为大多数可访问的文档都使用这种方法。
翻译:https://fadamakis.com/the-5-ways-to-define-a-component-in-vue-3-aeb01ac6f39f
本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!
 
 Vuetify 支持SSR(服务端渲染),SPA(单页应用程序),PWA(渐进式Web应用程序)和标准HTML页面。 Vuetify是一个渐进式的框架,试图推动前端开发发展到一个新的水平。
通过给组件传递参数, 可以让组件变得更加可扩展, 组件内使用props接收参数,slot的使用就像它的名字一样, 在组件内定义一块空间。在组件外, 我们可以往插槽里填入任何元素。slot-scope的作用就是把组件内的数据带出来
函数子组件(FaCC )与高阶组件做的事情很相似, 都是对原来的组件进行了加强,类似装饰者。FaCC,利用了react中children可以是任何元素,包括函数的特性,那么到底是如何进行增强呢?
 
 在现代的三大框架中,其中两个Vue和React框架,组件间传值方式有哪些?组件间的传值是灵活的,可以有多种途径,父子组件同样可以使用EventBus,Vuex或者Redux
自定义指令:以v开头,如:v-mybind。bind的作用是定义一个在绑定时执行一次的初始化动作,观察bind函数,它将指令绑定的DOM作为一个参数,在函数体中,直接操作DOM节点为input赋值。
prop的定义:在没有状态管理机制的时候,prop属性是组件之间主要的通信方式,prop属性其实是一个对象,在这个对象里可以定义一些数据,而这些数据可以通过父组件传递给子组件。 prop属性中可以定义属性的类型,也可以定义属性的初始值。
Web组件由三个独立的技术组成:自定义元素。很简单,这些是完全有效的HTML元素,包含使用一组JavaScript API制作的自定义模板,行为和标记名称(例如,<one-dialog>)。
web组件可以直接或间接的调用其他web资源。一个web组件通过内嵌返回客户端内容的另一个web资源的url来间接调用其他web资源。在执行时,一个web资源通过包含另一个资源的内容或者转发请求到另一个资源直接调用。
在实际开发项目中,有时我们会用到自定义按钮;因为一个项目中,众多的页面,为了统一风格,我们会重复用到很多相同或相似的按钮,这时候,自定义按钮组件就派上了大用场,我们把定义好的按钮组件导出,在全局引用,就可以在其他组件随意使用啦,这样可以大幅度的提高我们的工作效率。
Vue中子组件调用父组件的方法,这里有三种方法提供参考,第一种方法是直接在子组件中通过this.$parent.event来调用父组件的方法,第二种方法是在子组件里用$emit向父组件触发一个事件,父组件监听这个事件就行了。
内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!