vue3.0組件數(shù)據(jù)定義

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ù)之前。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容