美文网首页
vue3.0数组清空与重新赋值

vue3.0数组清空与重新赋值

作者: 来了啊小老弟 | 来源:发表于2021-11-12 09:48 被阅读0次

    记个踩坑笔记

    <template>
      <div>
        {{list}}
        <button @click="add">增加</button>
        <button @click="clearAll">清空</button>
        {{newList}}
      </div>
    </template>
    
    <script>
    import { ref, watch, toRefs,computed,reactive,onBeforeUpdate,onUpdated,onBeforeMount,onMounted,onBeforeUnmount,onUnmounted ,onRenderTracked,onRenderTriggered  } from 'vue'
    export default {
      name: '',
      components: {
    
      },
      setup(){
        let list = ref([])
        function add(){
          list.value.push(123)
          state.newList.push(123)
        }
        let state = reactive({
          newList:[]
        })
        function clearAll(){
          list.value = [1,2,3,4,5]
          // list.length = 0
          state.newList = []
          console.log(list)
        } 
        return {
          list,
          add,
          clearAll,
          ...toRefs(state)
        }
      },
    }
    </script>
    

    vue3.0里面,如果数组是用reactive()声明的,要清空数组得用list.length = 0,如果想要使用list =[],或者直接赋值类型list = [1,2,3,4,5],得把数组用ref([])来声明,然后用list.value = []来修改,然后如果是对象里面的数组,可以直接使用obj.list = []来清空,因为obj已经被响应式了.

    相关文章

      网友评论

          本文标题:vue3.0数组清空与重新赋值

          本文链接:https://www.haomeiwen.com/subject/wpbnzltx.html