Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

vue3项目中数组变化的更新问题

<div :class='["tab-item", menu.isShow === 1 ? "tab-item-on" : ""]' v-for='(menu, idx) in menuList' :key='idx'>
  <div class="tab-tl" @click='showTab(idx)'>{{menu.name}}</div>
  <div :class='["tab-icon", menu.isShow === 1 ? "" : "tab-icon-off"]' @click='delTab(idx)'>X</div>
</div>

setup() {
let menuDefault: MenuSave[] = [
  {
    name: '首页',
    isShow: 0,
    urlName: 'Home'
  }, {
    name: '会员1',
    isShow: 0,
    urlName: 'Leaguer'
  }, {
    name: '会员2',
    isShow: 0,
    urlName: 'Leaguer'
  }, {
    name: '会员',
    isShow: 1,
    urlName: 'Leaguer'
  }
]
let menuList = reactive(menuDefault)

function showTab (idx) {
  menuList = menuList.map((i, k) => {
    if (k === idx) {
      i.isShow = 1
    }
    return i
  })
  console.log('show', menuList)
}

function delTab (idx) {
  menuList = menuList.filter((i, k) => k !== idx)
  console.log('del', menuList)
}

return {
  menuList,
  showTab,
  delTab
}
问题是:
1、 用reactive创建了一个响应式数组,后台console打印出来可见数组也发生变化,但是页面上监听不到,显示的依然是原来的内容
2、 用ref创建响应式数组,则无法使用数组的方法如map、filter等
请问各位大神有何高见???

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

1、页面监听不到是因为你改的是变量,而不是return出去的对象数据。
vue监听的是return出去的对象。你改变量是没用的,变量不过是一个指针,你把指针重新指向一堆新数据并不会使得对象上的属性指向也改变。你可以先定义一个return的变量为result = {menuList};通过更改result.menuList来更改。
2、ref可以使用数组的方法,ref包装了一层,实际需要用.value形式访问数据。即menuList.value,value才是指向真实的数据


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...