账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    vuex中怎样使用this.$set更新对象?
    25
    0

    mutations是在一个独立的js文件里面 直接使用this.$set更新state对象数据会报错this.$set is not a function 这种情况怎么办呢?

    state里面的数据

    articleList: [
        {
          userinfo: {image: 'static/img/3.jpeg', nickname: 'eee', text: '嘿嘿', time: '十天前'},
          content: {href: '2222222', text: 'test', create_time: '', updata_time: ''},
          pic: [{path: 'static/img/0.jpg'}, {path: 'static/img/0.jpg'}, {path: 'static/img/0.jpg'}],
          likebar: {hot: 555, status: false, comments: 666},
          isFollow: true
        }
      ]

    组件中触发action
    this.$store.dispatch('getLists')

    action.js

    getLists (val) {
        api.articleList().then((res) => {
          val.commit('updateList', res)
        })
    }

    mutations.js

    updateList (state, data) {
        this.$set(this.state.articleList, 0, data)  //这样写不对
        this.state.articleList = data //这样写视图不更新
    }
    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 轩辕神邸 普通会员 1楼

      在Vue中,this.$set方法用于更新对象。这是一个常用的方法,可以帮助你更新组件中的数据。

      例如,假设你有一个名为user的数组,它包含一些用户对象。你可以使用this.$set方法来更新数组中的某个对象。

      ```javascript // 创建一个用户对象 const user = { name: 'John', age: 30, email: 'john@example.com' };

      // 使用$set方法更新数组中的某个对象 this.$set(user, 'name', 'Jane'); ```

      在这个例子中,user对象现在包含一个新的名为name的属性,其值为'Jane'

      注意,this.$set方法不会影响状态管理器的引用,而是会更新数组中的每个对象。如果你需要影响状态管理器的引用,你应该使用this.$set方法的箭头版本(this.$set())。

      javascript // 使用箭头版本更新数组中的某个对象 this.$set(user, 'age', 35);

      在这个例子中,user的状态管理器的引用被更新,但并不会影响数据。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部