背景: 因为不同人写代码的风格不一样,有些使用选项式,有些使用组合式,导致接手别人代码时有时风格一时没适应会造成混乱,故总结 vue 文件的各种写法及其当父子组件传值的写法
1. 选项式
<template>
<div>{{ count }}</div>
<button @click="increment">增加</button>
</template>
<script>
export default {
name: 'MyVue',
// data() 返回的属性将会成为响应式的状态
// 并且暴露在 `this` 上
data() {
return {
count: 0
}
},
// methods 是一些用来更改状态与触发更新的函数
// 它们可以在模板中作为事件处理器绑定
methods: {
increment() {
this.count = this.count + this.addStep
// 子给父元素穿着,直接通过this调用$emit
this.$emit('hanldeClick', this.count)
}
},
// 生命周期钩子会在组件生命周期的各个不同阶段被调用
// 例如这个函数就会在组件挂载完成后被调用
mounted() {
console.log(`The initial count is ${this.count}`)
},
// 父组件传值,调用也使用 this 直接调用
props: {
addStep: {
type: Number,
default: 1
}
},
// 子组件传的值
emits: ['hanldeClick']
}
</script>
<style lang=""></style>
2. 组合式
2.1 setup 写入
<template>
<div>{{ count }}</div>
<button @click="increment">增加</button>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
// 定义父组件传过来的值
const props = defineProps({
addStep: {
type: Number,
default: 1
}
})
// 定义传给父组件的事件
const emits = defineEmits(['hanldeClick'])
// 如果需要响应式需要借助 ref 或者 reactive, 其中使用 ref 中的值时需要先调用 .value
const count = ref<number>(0)
// 自定义方法
const increment = (): void => {
// 使用父组件传过来的数据使用 props 调用,props 可以随意取名,这里只是保持一致
count.value = count.value + props.addStep
emits('hanldeClick', count.value)
}
onMounted(() => {
console.log(`The initial count is ${count.value}`)
})
</script>
<style scoped lang="scss"></style>
2.2 setup 不写入
<template>
<div>{{ count }}</div>
<button @click="increment">增加</button>
</template>
<script lang="ts">
import { ref } from 'vue'
export default {
name: 'MyVue',
// 父组件传值
props: {
addStep: {
type: Number,
default: 1
}
},
// 传给父组件的方法
emits: ['hanldeClick'],
// setup 不写入 <script> 标签时,接受两个参数: props 和 content
// porps 就是父组件传过来的值,使用时需要现在 setup 中定义才可以使用
// content 中包括 attrs,slots,emit
setup(props, content) {
const { emit } = content
const count = ref(0)
const increment = (): void => {
count.value = count.value + props.addStep
emit('hanldeClick', count.value)
}
return { count, increment }
}
}
</script>
<style scoped lang="scss"></style>
3. defineComponent
defineComponent 这里拿出来是因为其既可以在选项式中使用,也可以在组合式中使用,但是注意,在组合式中使用时,只能使用组合式中的第二种情况,也就是 setup 不写入
<template>
<div>{{ count }}</div>
<button @click="increment">增加</button>
</template>
<script>
import { defineComponent } from 'vue'
export default defineComponent({
...
})
</script>
<style scoped lang="scss"></style>