1.ref() 函数
ref() 函数用来根据给定的值创建一个响应式的数据对象,传入的为基本数据类型,例如字符串、数字、boolean 等,返回值是一个对象,这个对象上只包含一个 value 属性
ref定义的变量,改变值要.value,而且在template中不用写.value
<div>{{msg}}</div>
<button @click="changeMsg()">修改msg</button>
import {reactive,ref,toRefs} from 'vue'
setup() {
//定义
const msg = ref('你好')
//修改
const changeMsg =()=>{
msg.value ='msg被改了'
}
//导出
return {
msg,
changeMsg
}
}
复制代码
2、reactive() 函数
reactive函数传入的为引用类型,例如数组、对象等,但不能代理基本类型值,返回一个响应式的数据对象, 想要使用创建的响应式数据也很简单,创建出来之后,在setup中return出去,直接在template中调用即可。
<div>{{state.msg}}</div>
<button @click="changeMsg()">修改msg</button>
import { reactive, ref, toRefs } from 'vue'
setup() {
//定义
const state = reactive({
msg: '你好',
msg2:'hello'
})
//修改
const changeMsg = () => {
state.msg = 'msg被改了'
}
//导出
return {
state,
changeMsg
}
}
复制代码
3、toRefs() 函数
toRefs() 函数可以将 reactive() 创建出来的响应式对象,转换为普通的对象,相当于变成一个个的ref(),类似使用拓展用算符…的方法返回数据data
使用toRefs和reactive()区别在于可以直接使用msg属性,不用state.
<div>{{msg}}</div>
<button @click="changeMsg()">修改msg</button>
import { reactive, ref, toRefs } from 'vue'
setup() {
//定义
const state = reactive({
msg: '你好',
msg2:'hello'
})
//修改
const changeMsg = () => {
state.msg = 'msg被改了'
}
//导出
return {
...toRefs(state),
changeMsg
}
}
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END