vue3学习之路

2023-12-25 22:26:21

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'
})

文章来源:https://blog.csdn.net/weixin_41254345/article/details/135205786
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。