API 风格
选项式 API (Options API)
<script>
export default {
name: 'MyComponent',
props: ['title'],
props: {
title: String,
},
props: {
propA: String,
propB: [String, Number],
propC: {
type: Number,
default: 100
},
},
data() {
return {
count: 0
}
},
beforeCreate() {
console.log('beforeCreate');
},
created() {
console.log('created');
},
beforeMount() {
console.log('beforeMount');
},
mounted() {
console.log('mounted');
},
beforeUpdate() {
console.log('beforeUpdate');
},
updated() {
console.log('updated');
},
beforeDestroy() {
console.log('beforeDestroy');
},
destroyed() {
console.log('destroyed');
},
computed: {
reversedMessage() {
return this.message.split('').reverse().join('');
}
},
watch: {
message(newVal, oldVal) {
console.log(`message changed from ${oldVal} to ${newVal}`);
}
},
methods: {
increment() {
this.count++
}
},
}
</script>
组合式 API (Composition API)
- vue2的写法
- 在单文件组件中,组合式 API 通常会与 <\script setup> 搭配使用
- 基础写法
<script setup>
import { toRefs, toRef } from 'vue'
export default {
props: {
title: String
},
setup(props,context) {
const count = ref('1')
const name = ref('我的名字')
return {
count,
name
}
},
mounted() {
console.log(this.count)
console.log(this.name)
}
}
</script>
<script setup>
import { ref, onMounted } from 'vue'
const count = ref(0)
function increment() {
count.value++
}
onMounted(() => {
console.log(`The initial count is ${count.value}.`)
})
</script>