ref
基本数据类型
number、boolean、string等等使用的方式都跟下面类似;底层实现响应式也是对象,有兴趣的朋友可以去看源码
<template>
<div>{{ counter }}</div>
<button @click="add">+</button>
<button @click="increment">-</button>
</template>
<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
const counter = ref(0)
const add = () => {
counter.value += 1
}
function increment() {
if(counter.value <= 0) {
ElMessage({
message: 'counter不能小于0',
type: 'warning',
})
return
}
counter.value -= 1
}
</script>
引用数据类型
<template>
<div v-for="(item, index) in names" :key="index">{{ item }}</div>
<button @click="addUser">添加用户</button>
</template>
<script setup>
import { ref } from 'vue'
const names = ref(['张三'])
function addUser() {
names.value.push('李四')
}
</script>
动态添加、删除属性
<template>
<div v-for="(item, index) in user" :key="index">{{ item }}</div>
<div>
<button @click="addUserInfo" style="padding-right: 6px;">添加用户信息</button>
<button @click="removeUserInfo">删除用户信息</button>
</div>
</template>
<script setup>
import { ref } from 'vue'
const user = ref({})
function addUserInfo() {
user.value = {
name: 'alan',
age: 18
}
}
function removeUserInfo() {
delete user.value.age
}
</script>
获取dom、组件实例
父组件
<template>
<div>
<div ref="domRef">Hello Vue !!</div>
<div style="margin-bottom: 20px;">
<el-button @click="editDomText">换一个</el-button>
</div>
<ChildCom ref="child1" />
<el-button @click="getChildContent">获取子组件方法和数据</el-button>
</div>
</template>
<script setup>
import ChildCom from './components/childCom.vue';
const domRef= ref(null)
const child1 = ref(null)
const editDomText = () => {
domRef.value.textContent = 'Hello Alan'
}
function getChildContent() {
console.log('运行子组件方法');
child1.value.childFun()
console.log('获取子组件响应式数据', child1.value.user);
console.log('获取子组件dom内容');
console.log(child1.value.getChildDomData());
}
</script>
子组件
<template>
<div>
<div ref="child">这是子组件的ref</div>
</div>
</template>
<script setup>
import {ref} from 'vue'
const child = ref(null)
const user = ref({
username: 'alan',
age: 18
})
function childFun() {
console.log('这是子组件方法');
}
function getChildDomData() {
const text = child.value.textContent
return text
}
// 暴露子组件的方法、属性等
defineExpose({
childFun,
user,
getChildDomData
})
</script>
reactive
reactive(attr)只能把Array、Object等了类型作为实参,不能传入基本数据类型
<template>
<div v-for="(item, index) in data" :key="index">{{ item }}</div>
<div>
<button @click="addUserInfo" style="padding-right: 6px;">添加用户信息</button>
<button @click="removeUserInfo">删除用户信息</button>
</div>
</template>
<script setup>
import { reactive } from 'vue'
const data = reactive([])
const data = reactive({
username: 'alan'
})
data.push('张三')
function addUserInfo() {
data.push('李四')
}
function removeUserInfo() {
delete data[0]
}
</script>