uniapp中使用vue3进行开发。
使用rective 进行响应式,数据请求后,重新赋值,却不能更新。代码如下: <template> <view class="content"> <image class="logo" src="/static/logo.png"></image> <view class="text-area"> <text class="title">{ { title } }</text> <text class="title">{ { count } }</text> <text class="title">{ { money } }</text> </view> <view v-for="item in list" :key="id"> { { item.stuNo } } { { item.stuName } } </view> </view> </template> <script> import { ref,reactive,getCurrentInstance,onMounted,toRefs } from 'vue' export default { setup(){ const title = ref("v3 写uniapp"); const data = reactive({ count:666, money:1000000, list:[] }) const {proxy} = getCurrentInstance(); onMounted(()=>{ proxy.$http({ url:"/getList", data:{ user:"doubleyong", pwd:"888888" } }).then((res)=>{ console.log(res.data); data.list =res.data.data; }).catch((err)=>{ console.log(err); }); }) return {title, ...data} } } </script> 响应式不生效原因: 使用三个点解构后,响应式失效了。 解决方案: 方案一: 使用toRefs将,reactive对象转到多个Refs,视图代码不变. 只在return 时,用...toRefs把reactive对象包起来 <template> <view class="content"> <image class="logo" src="/static/logo.png"></image> <view class="text-area"> <text class="title">{ { title } }</text> <text class="title">{ { count } }</text> <text class="title">{ { money } }</text> </view> <view v-for="item in list" :key="id"> { { item.stuNo } } { { item.stuName } } </view> </view> </template> <script> import { ref,reactive,getCurrentInstance,onMounted,toRefs } from 'vue' export default { setup(){ const title = ref("v3 写uniapp"); const data = reactive({ count:666, money:1000000, list:[] }) const {proxy} = getCurrentInstance(); onMounted(()=>{ proxy.$http({ url:"/getList", data:{ user:"doubleyong", pwd:"888888" } }).then((res)=>{ console.log(res.data); data.list =res.data.data; }).catch((err)=>{ console.log(err); }); }) return {title, ...toRefs(data)} } } </script> 方法二: 就使用使reactive对象,js代码不变,视图代码如下: <template> <view class="content"> <image class="logo" src="/static/logo.png"></image> <view class="text-area"> <text class="title">{ { title } }</text> <text class="title">{ { data.count } }</text> <text class="title">{ { data.money } }</text> </view> <view v-for="item in data.list" :key="id"> { { item.stuNo } } { { item.stuName } } </view> </view> </template> <script> import { ref,reactive,getCurrentInstance,onMounted,toRefs } from 'vue' export default { setup(){ const title = ref("v3 写uniapp"); const data = reactive({ count:666, money:1000000, list:[] }) const {proxy} = getCurrentInstance(); onMounted(()=>{ proxy.$http({ url:"/getList", data:{ user:"doubleyong", pwd:"888888" } }).then((res)=>{ console.log(res.data); data.list =res.data.data; }).catch((err)=>{ console.log(err); }); }) return {title, data} } } </script> |
|
|