vue3.0入坑指南

  1. 定义组件
import {defineComponent} from 'vue'
export default defineComponent({
  name: '',
  props: {
  },
  components: {},
//所有定义的数据,都在setup函数里
  setup (props, ctx) {
    return {
    }
  }
})
  1. ref定义单个数据
import {ref} from 'vue'
let num = ref(10)
let name = ref('jack')
let arr = ref(['a','b','c'])
 setup (props, ctx) {
    return {
      num,
      name 
    }
  }

3.reactive定义对象类型的数据

import {reactive} from 'vue'
let data = reactive({
  age: 10,
  obj: {
    price: 20
  }
})
 setup (props, ctx) {
    return {
     data 
    }
  }
{{data.age}}
{{data.obj.price}}
import {reactive, toRefs} from 'vue'
let data = reactive({
  age: 10,
  obj: {
    price: 20
  }
})
 setup (props, ctx) {
    return {
     ...toRefs(data)
    }
  }
{{age}}
{{obj.price}}
  1. 方法的定义和使用
let clickNum = () => {
// 访问ref定义的数据,要写数据名.value
 console.log(age.value)
// 访问reactive定义的,要写定义的数据名
console.log(data.age)
}

let clickData = (val) => {
  console.log(val)
}  
 setup (props, ctx) {
    return {
     clickNum,
     clickData 
    }
  }
  1. 计算属性
import {computed} from 'vue'
let num = ref(10)
let addNum = computed(() => {
  return num.value
})
setup (props, ctx) {
    return {
     addNum 
    }
 }
  1. 状态管理
import {createStore} from 'vuex
export default createStore({
  state: {
    name: 'Jack',
  },
  mutations: {
   changeName (state, payload) {
     state.name = payload
   }
  },
 actions: {
   setName (store, params) {
    store.commit('changeName', params)
   }
 }
})
import {useStore} from 'vuex'
setup (props, ctx) {
    let store = useStore()
    let list = computed(() => {
        return store.state.list
    })
    return {
     list 
    }
 }
  1. 跳转路由
import {useRouter, useRoute} from 'vue-router'
setup (props, ctx) {
   // 全局路由对象
    let router= useRouter()
   // 当前路由对象
    let route = useRoute()
   console.log(route.query)
    let goTo = () => {
      router.push({
        path: '/about'
      })
    }
    return {
     goTo 
    }
 }
  1. 组件生命周期
// 组件初始化
setup
//组件挂载的过程
onMounted
// 常用来发请求,做数据初始化的操作,接收路由传递的参数
onMounted(() => {
})
// 组件卸载时触发,清除定时器等
onUnmounted
onUnmounted(() => {})

你可能感兴趣的:(vue3.0入坑指南)