1. 定義
維護單一功能,可復(fù)用的單個個體。
2. 結(jié)構(gòu)
<template></template>
<script></script>
<style></style scoped lang='scss'>
其中scoped,只在當前組件生效。
3. 定義組件
//從vue中導(dǎo)入定義組件的方法,就是defineComponent
import { defineComponent,reactive } from 'vue'
//ES6導(dǎo)出模塊,defineComponent方法,內(nèi)部是一個對象。
export default defineComponent({
name:"Home",//定義組件的名稱
//接收父組件的數(shù)據(jù)
props:{
},
//定義子組件
component:{
},
//setup函數(shù),
setup(props,ctx) {
return {
}
})
4. 定義單個數(shù)據(jù)ref
(1)引入
import { defineComponent,reactive,ref } from 'vue'
(2) 定義數(shù)據(jù)并初始化
setup(props,ctx) {
let num = ref(10);
let name = ref('wuning');
return {
}
(3) 暴漏出去
setup(props,ctx) {
let num = ref(10);
let name = ref('wuning');
let arr = ref([1,2,3])//定義數(shù)組,并初始化
let obj = ref({
age:20,
})//定義對象
return {
num,//es6簡寫方式
name,
arr,
obj
}
(4)使用方法---插值表達式
<div>
{{name}}
{{num}}
</div>
5. 定義方法
vue3中已經(jīng)沒有method對象了。使用聲明式定義一個函數(shù)。ES6中的知識。
(1) 定義
setup(props,ctx) {
//定義數(shù)據(jù),并初始化
let num = ref(10)
let data = reactive({name:"wuning"})
//定義方法
let add=()=>{
//訪問ref定義的數(shù)據(jù),需用num.value的形式拿到。
//訪問reactive定義的數(shù)據(jù)使用,data.name
}
//暴漏出去
return {
...toRef(data),
num,
add
}
}
數(shù)據(jù)和方法都是在setup中定義的,然后通過export導(dǎo)出模塊。
(2)方法之間的調(diào)用
方法之間的調(diào)用,必須先定義在被調(diào)用,被掉用的函數(shù)要在調(diào)用的函數(shù)之前。