vue3学习之路

reactive, ref响应式数据

let num = reactive(0)// reactive中是简单数据类型,不会自动响应到页面中,除非有对象类型要响应才会跟着响应到页面
const obj = reactive({
  num: 0,
  name: 'malinshu'
})

const add = () => {
  num++;
  obj.num++;
  obj.name = obj.name + '--'
}

let activeNum = ref(0) // ref 对简单数据类型有响应到页面
const addNum = () => {
  activeNum.value++
}

const activeObj = ref({
  age: 18,
  name: '码林鼠'
})

const modifyObj = () => {
  activeObj.value.age++;
  activeObj.value.name = activeObj.value.name + '--'
}
<div>{{ num }},{{ obj.num }},{{ obj.name }},{{ activeNum }},{{ activeObj.age }},{{ activeObj.name }}</div>

computed计算属性

const newNum = computed(() => {
  return activeNum.value * 2
})
<div>{{ newNum }}</div>

watch监听属性,可以监听多个

import {watch, ref} from 'vue'

const num = ref(0)
const num2 = ref(0)

watch(num, (newV, oldV) => {
  console.log(newV,oldV)
})

const addNum = () => {
  num.value++
  num2.value = num2.value + 2
}


watch([num, num2], ([numNew, num2New], [numOld, num2Old]) => {
  console.log(numNew, num2New,numOld, num2Old)
})

生命周期函数

setup
onBeforeMount, onMounted
onBeforeUpdate, onUpdated
onBeforeUnmount, onUnmounted

父子通讯

father.vue

import Son from './Son.vue'
import {ref} from 'vue'
const num = ref(0)

const addNum = () => {
  num.value++
}

const getFromSon = () => {
  num.value = num.value + 10
}

<Son name="malinshu" :number="num" @get-from-son="getFromSon"></Son>
  <button @click="addNum">递增</button>

son.vue

import { defineProps, defineEmits } from 'vue';

const props = defineProps({
    name: String,
    number: Number
})

const emit = defineEmits(['get-from-son'])

const sonClick = () => {
    emit('get-from-son', 'hello, i am son')// 通过触发事件来实现子传父
}
<div>i am the fucking son of {{ name }},i am {{ number }} years old.</div>
    <button @click="sonClick">son button</button>

子组件向外暴露变量和方法

father.vue

const refObj = ref(null)// 通过ref来获取dom实例
const clickSonMethod = () => {
  refObj.value.outputMethod()
}

  <Son ref="refObj"></Son>
  <button @click="clickSonMethod">递增</button>

son.vue

const outputMethod = () => {
    console.log('暴露出的方法')
}

defineExpose({
    outputMethod
})

跨层级传递数据

grandfather.vue

const color = ref('pink')
provide('theme-color', color.value)
provide('provice-action', () => {
  console.log("hello grandfather")
})

grandson.vue

import {inject} from 'vue'
const color = inject('theme-color')
const hello = inject('provice-action')
<button @click="hello">hello</button>

defineOptions定义setup的平级属性,vue3.3以上

defineOptions({
	name:'componentName'
})
  • 11
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值