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>
const newNum = computed(() => {
return activeNum.value * 2
})
<div>{{ newNum }}</div>
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({
name:'componentName'
})